首页 > 解决方案 > watch(provider) 是否更新父窗口小部件的子窗口?

问题描述

我正在尝试使用一个 UserInteraction 更新两个页面,因此尝试使用 Riverpod 库访问两个页面中的相同流。

现在进一步解释一下。当我将 Stream 传递给CustomerPage我能够获取数据(字符串 Anton)。当我单击触发 FireStore 更改的按钮ParentWidget时,当我返回到它时,字符串会更新为 中的“Marco”。但它不会改变,CustomerPage除非我通过 ParentWidget 中的 RaisedButton 重新打开页面。但是我希望它在单击 CustomerPage 上的 Button 后更新

我希望这能让它更清楚。

class ParentWidget extends ConsumerWidget{
Widget build(BuildContext context, ScopedReader watch){
Stream<DocumentSnapshot> doc = watch(streamProvider.stream);
return Container(
child: Column(
  children: [ 
      Text(doc.name), //Lets say the name is Anton,
      RaisedButton(
         child: Text(" road to CustomerPage"),
         onPressed:(){
             Navigator.of(context).pushNamed(RouteGenerator.customerPage, arguments: doc);
     },), //RaisedButton
   ],), //Column
   );  //Container
  }
 }

class CustomerPage extends StatelessWidget{
   Stream<DocumentSnapshot> docStream
   CustomerPage({this.docStream});
   Widget build(BuildContext context){
   return Column(
        children: [ 
          Text(docStream.name) //Here is also Anton
          RaisedButton(
              child: Text("Change Name"),
              onPressed: () {
                  context.read(streamProvider).changeName("Marco"); 
            },), //RaisedButton
         ]
       ); //Column
      }
}

标签: flutterriverpod

解决方案


到目前为止我的理解是,riverpod 允许您获取提供者的状态,这基本上是一个值(?),这就是为什么只需在您想要访问其数据的任何小部件中观看它就足够了。不再需要(仅就我而言)让小部件在应用程序中传递。

下面是我认为正确的解决方案。

我给提供者打了多少次电话也没关系。它总是相同的实例。就我而言,这意味着 doc 和 doc2 是相同的。我希望这能让它更清楚。

class ParentWidget extends ConsumerWidget{
Widget build(BuildContext context, ScopedReader watch){
Stream<DocumentSnapshot> doc = watch(streamProvider.stream);
return Container(
child: Column(
  children: [ 
      Text(doc.name), //Lets say the name is Anton,
      RaisedButton(
         child: Text(" road to CustomerPage"),
         onPressed:(){
             Navigator.of(context).pushNamed(RouteGenerator.customerPage);
     },), //RaisedButton
   ],), //Column
   );  //Container
  }
 }

class CustomerPage extends ConsumerWidget{
Widget build(BuildContext context, ScopedReader watch){
 Stream<DocumentSnapshot> doc2 = watch(streamProvider.stream);
   return Column(
        children: [ 
          Text(doc2.name) //Here is also Anton
          RaisedButton(
              child: Text("Change Name"),
              onPressed: () {
                  context.read(streamProvider).changeName("Marco"); 
            },), //RaisedButton
         ]
       ); //Column
      }
}

推荐阅读