我是Flutter的新手,并且正在关注Flutter的官方教程,以学习Flutter的基础知识。
因此,我想创建一个名为“CustomCard”的可重用组件,并这样做:
class CustomCard extends StatelessWidget {
CustomCard({@required this.index, @required this.onPress});
final index;
final Function onPress;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: <Widget>[
Text('Card $index'),
FlatButton(
child: const Text('Press'),
onPressed: this.onPress,
)
],
),
);
}
}
现在,要在MyApp中使用它,我做到了:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to flutter',
home: Scaffold(
appBar: AppBar(
title: Text('hello'),
),
body: Center(
child: Text('centre'),
CustomCard(
index:'card1',
onPress: print(' this is $index')
),
),
),
);
}
}
现在我的IDE说:
The method 'CustonCard' isn't defined for the class 'MyApp'.
如何解决呢?
终端错误:
Compiler message:
lib/main.dart:17:6: Error: Place positional arguments before named arguments.
Try moving the positional argument before the named arguments, or add a name to the argument.
CustomCard(
^^^^^^^^^^
lib/main.dart:17:6: Error: Expected named argument.
CustomCard(
^
lib/main.dart:15:21: Error: No named parameter with the name '#1'.
body: Center(
^^...
/C:/src/flutter/packages/flutter/lib/src/widgets/basic.dart:1863:9: Context: Found this candidate, but the arguments don't match.
const Center({ Key key, double widthFactor, double heightFactor, Widget child })
编辑:更正了拼写错误。还添加控制台日志。
最佳答案
您会遇到一些错误,但是请不要担心它会在一开始就发生。因此,让我们进入问题:
首先,您在体内定义了一个中心小部件,该中心小部件仅允许一个 child 进入,但您尝试放置两个小部件(文本和自定义卡片)。因此,要同时放置两个小部件,可以将其更改为如下所示:
Center(
child: Column(
children: <Widget>[
Text('centre'),
CustomCard(...)
],
),
),
此外,请注意onPress函数将Function作为参数,但是您传递的print(...)结果无效。只需将其更改为:
CustomCard(index: index, onPress: () => print(' this is $index'))
最后,我认为您错过了定义索引变量的机会。只需添加:
String index = "card1";
关于flutter - 如何在Flutter中使用自定义小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61206630/