[英]In Flutter, how can I read data from a child widget when callbacks are not available within the build method of the child?
I have an AppBar button where I want to read a childData list and do something with it:我有一个 AppBar 按钮,我想在其中读取 childData 列表并对其进行处理:
class _ParentState extends State<Parent> {
....
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: Icon(Icons.add),
onPressed: () async {
//Need to access childData data here
print(childData); //currently prints null
},
),
],
),
body: SafeArea(
child: Column(
children: <Widget>[
ChildWidget(),
],
The ChildWidget uses a StreamBuilder and which loops through the snapshots and does something else before appending the snapshot to the list: ChildWidget 使用 StreamBuilder 并遍历快照并在将快照附加到列表之前执行其他操作:
class ChildWidgetState extends State<ChildWidget> {
....
Widget build(BuildContext context) {
return StreamBuilder<List<DocumentSnapshot>>(
stream: stream,
builder: (context, snapshots) {
if (snapshots.connectionState == ConnectionState.active &&
snapshots.hasData) {
List<DocumentSnapshot> childData = [];
for (var x in snapshots.data) {
//do something else with snapshot data
childData.add(x);
}
I have tried to use a callback function where I notify the parent widget to refresh, but this gives a setState() or markNeedsBuild() called during build
error as it setStates during the build method of the ChildWidget.我尝试使用回调 function 通知父小部件刷新,但这会setState() or markNeedsBuild() called during build
因为它在 ChildWidget 的构建方法期间设置状态。 I definitely have data within my streambuilder as this is used elsewhere with no issues currently.我的流构建器中肯定有数据,因为它在其他地方使用,目前没有问题。
A state management package like Provider only seems to provide data to child widgets, not pass them back up, and I've read that using global variables is frowned upon.像 Provider 这样的 state 管理 package 似乎只向子小部件提供数据,而不是将它们传递回去,而且我读过使用全局变量是不受欢迎的。 Would it also be bad practice to add the childData list to a database package like Hive and then read that in my ParentWidget?将 childData 列表添加到数据库 package (如 Hive)然后在我的 ParentWidget 中读取它是否也是不好的做法? I don't necessarily want to rebuild the parent widget - just read the data within the child widget when I click my AppBar button.我不一定要重建父小部件 - 只需在单击 AppBar 按钮时读取子小部件中的数据。
Thanks.谢谢。
You can use provider to get data in the parent widget您可以使用 provider 在父窗口小部件中获取数据
Provider(
create: (_) => MyModel(),
child: ParentWidget()
)
on ChildWidget use关于 ChildWidget 的使用
data=Provider.of<MyModel>(context);
and MyModel()
can be data class containing data you want to get in your parent appBar
.和MyModel()
可以是数据 class 包含您想在父appBar
中获取的数据。
Now in steam builder you can use现在在 Steam Builder 中,您可以使用
data.childData=newData
And after that using之后使用
data=Provider.of<MyModel>(context);
In parent widget and在父小部件和
data.childData
Will have newdata
you want. newdata
你想要的新数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.