我想将一些小部件作为参数传递给功能,flutter支持吗?下面是我的代码。我应该将小部件作为参数传递给功能吗?
这是我想作为参数传递的小部件:
class FirstWidget extends StatelessWidget {
@override
Widget build(BuildContext context){
return Container(
child: Text('i am the first'),
);
}
}
class SecondWidget extends StatelessWidget {
@override
Widget build(BuildContext context){
return Container(
child: Text('i am the second'),
);
}
}
createWidget
很重要:
class Main extends StatelessWidget {
// maybe return a widget i wanna, maybe return a default widget.
Widget _createWidget(widget){
// do something to judge
if(dosomething){
return Container(
child: Text('nothing'),
);
}
// i wanna `widget()` at this postion. not when `_createWidget`
return widget();
}
@override
Widget build(BuildContext context){
return Column(
children: <Widget>[
_createWidget(FirstWidget),
_createWidget(SecondWidget),
],
);
}
}
答案 0 :(得分:1)
您可以将Widget
的实例传递给函数,然后将其返回:
@override
Widget build(BuildContext context){
return Column(
children: <Widget>[
_createWidget(FirstWidget()),
_createWidget(SecondWidget()),
],
);
}
Widget _createWidget(Widget widget) {
// ... other stuff...
return widget;
}
或者如果您想将FirstWidget()
和SecondWidget()
的构建推迟到之后,则您致电_createWidget()
(例如,如果您想要{{1} }以有条件地返回构造的窗口小部件),则可以使用匿名函数创建thunk:
_createWidget
答案 1 :(得分:0)
您可以将任何内容传递给函数。 更改您的函数定义,如下所示:
Widget _createWidget(Widget child){
// do something to judge
if(dosomething){
return Container(
child: Text('nothing'),
);
}
// Notice that you just return the variable and not call it as a function.
// return child(); <-- this one will result in an error
return child; // <-- this is the right way
}