下面是一些伪代码,展示了我想要实现的目标:
Text txt(text, [subtitle = false]) {
final params = subtitle
? {
'textAlign': TextAlign.center,
'style': TextStyle(color: Colors.purple)
}
: {
'textAlign': TextAlign.left,
'style': TextStyle(color: Colors.black54)
};
return Text(
text,
...params,
);
}可以将变量参数传递给Flutter小部件吗?请记住,文本小部件只是一个示例,并不是我问题的焦点,它可以是任何其他的Flutter小部件,例如容器或SizedBox。
发布于 2021-09-02 02:53:31
如何使用变量将参数传递给小部件:
:我们必须稍微颠覆一下我们的想法。当您在目标小部件中使用带有默认值的最终参数导航到被调用的小部件时,可以将数据传递给该小部件。使用一个可选函数,您可以从“子”(目标)小部件中获取数据。
在目标有状态小部件中,创建最后一个变量;
final int boxIndex;在目标构造函数中,为final变量指定一个常量默认值
DestinationClassConstructor({Key? key, this.boxIndex = -1}): super(key: key);您可以将方法添加到有状态小部件类中,这些方法以一些重要的方式使用该值:
例如:
bool isEditing() {
return this.boxIndex != -1;
}在调用目标小部件的源小部件中,您可以传入一个不同于默认值的值。
DestinationClassConstructor(boxIndex: 123),在目标小部件状态内容类中,您可以直接使用该值或调用上面的方法:
例如:
widget.isEditing()
widget.boxIndex,当您决定可以将函数作为参数传递时,此方法的真正威力就会显现出来:
例如:
在目标有状态小部件中,使用其构造函数参数创建可为空的函数调用:
final Function()? destinationWidgetTapped;
DestinationClassConstructor({Key? key, this.destinationWidgetTapped}): super(key: key);注意:在这种情况下,函数变量被赋值为null。
在目标内容状态小部件中的某个位置调用函数:
if (widget.destinationTapped != null) widget.destinationWidgetTapped!();然后,在源小部件中进行如下调用:
DestinationClassConstructor(destinationWidgetTapped: () {
print('this code from the source widget executes after the child widget event is invoked');
Navigator.of(context).pop(); //pop the child widget
},当您考虑到您还可以在函数调用中传回值时,这是很好的,并且非常有用。
final Function(String)? destinationWidgetTapped;
DestinationClassConstructor({Key? key, this.destinationWidgetTapped}): super(key: key);在目标内容状态小部件中的某个位置调用函数:
if (widget.destinationTapped != null) widget.destinationWidgetTapped!('Hello from the Destination Content State Widget');然后你就可以像这样接收数据了:
DestinationClassConstructor(destinationWidgetTapped: (value) {
print('Data is passed from the destination widget with a string value of : $value');
Navigator.of(context).pop();
},Nota Bene:
也可以将Function(String)编写为ValueChanged<String>
我们可以进一步推断,任何对象都可以被传递:
编写为ValueChanged<Object?>的Function(Object?)
这个参数可能更好地写成:
最终的ValueChanged?onValueChanged;DestinationClassConstructor({Key?key,this.onValueChanged}):超级(key: key);
这将允许用户发送任何数据对象、数组、json、map、string、int、bool等,同时保持对完成处理程序的访问,以便可以双向访问变量数据。
发布于 2021-01-20 01:40:01
在我的一个应用程序中
Text(listItem.name,
style: TextStyle(
decoration: listItem.checked
? TextDecoration.lineThrough
: TextDecoration.none)),运行良好,listItem.checked是布尔型的。
这个问题有更多的例子:How to use conditional statement within child attribute of a Flutter Widget (Center Widget)
https://stackoverflow.com/questions/65796594
复制相似问题