watch(provider) 是否更新父小部件的子部件?

时间:2021-04-07 07:00:08

标签: flutter riverpod

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

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

我希望这能让你更清楚。

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 CostumerPage extends StatelessWidget{
   Stream<DocumentSnapshot> docStream
   CostumerPage({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
      }
}

1 个答案:

答案 0 :(得分:1)

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

我打电话给提供商的次数也无关紧要。它总是会是同一个实例。就我而言,这意味着 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, arguments: doc);
     },), //RaisedButton
   ],), //Column
   );  //Container
  }
 }

class CostumerPage 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
      }
}
相关问题