flutter - Flutter-在列内的自定义小部件之间传递数据
问题描述
我被一个WidgetA()
计算字符串的方法卡住了,但我想将此字符串传递给WidgetB()
- 如何将更新的数据传递给WidgetB
?
return Column(
children: [
WidgetA() // calculates value
WidgetB() // needs to use this value
],
);
Widget A 是一个服装类 Stateful Widget
解决方案
对我来说,最明显的方法是将数据存储在父窗口小部件的状态中。然后,您可以提供WidgetA
一个回调来设置此状态,并提供WidgetB
值:
int value;
setValue(int newValue) {
setState(() {
value = newValue;
});
}
return Column(
children: [
WidgetA(callback: (int newValue) => this.setValue(newValue)) // calculates value
WidgetB(value: this.value) // needs to use this value
],
);
WidgetA 和 WidgetB 可能如下所示:
class WidgetA extends StatelessWidget {
final Function callback;
// get the callback as a named argument
WidgetA({required this.callback});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
print('The button was pressed!');
// get the value and call the callback with it
callback(42);
},
child: Text('Press me!'));
}
}
class WidgetB extends StatelessWidget {
final int value;
WidgetB({required this.value});
@override
Widget build(BuildContext context) {
return Text('The number is $value');
}
}
根据值及其更新频率,也可以使用某种存储方式,例如值的共享首选项。
推荐阅读
- java - 无法使用 getName 从数组中获取要显示的名称
- python - 卡在素数上
- javascript - 使用 luxon 将 iso 8601 格式化为日期(YYYY-MM-DD)
- r - 如何将数据框列表转换为一个动物园对象R
- python - 列表中的字典条目变得相同
- python - 在 Python 中的消息对象上使用 get_body 时出现 AttributeError
- html - 如何以 HTML 格式发送到电子邮件?
- python - 外壳:管道文件到 python 标准输入并显示到屏幕
- javascript - 用 Jest 测试 Node.js API
- reactjs - 如何将请求 Axios 从 React JS 发布到 ASP.NET Core