如何使用变量将参数传递给小部件:
tldr;我们必须稍微改变一下思路。数据可以
当您使用 final 导航到它时传递给被调用的小部件
目标小部件中具有默认值的参数。使用
可选功能,您可以从“孩子”(目的地)取回数据
小部件。
在目标状态小部件中创建最终变量;
final int boxIndex;
在目标构造函数中,给最终变量一个常量默认值
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);
注意:在这种情况下,函数变量被赋予一个默认值
为空。
在您的目标内容状态小部件中的某处调用该函数:
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>
我们可以进一步推断可以传递任何对象:
Function(Object?)写成ValueChanged<Object?>
而论点最好写成:
final ValueChanged<Object?>? onValueChanged;
DestinationClassConstructor({Key? key, this.onValueChanged}): super(key: key);
这将允许发送任何数据对象、数组、json、地图、
string、int、bool 等,同时保持对完成的访问
处理程序,以便可以双向访问变量数据。