flutter-in-action icon indicating copy to clipboard operation
flutter-in-action copied to clipboard

《Flutter 实战》关于7.2章节 数据共享(InheritedWidget)的疑问

Open peng8934763 opened this issue 4 years ago • 4 comments

1、地址 https://book.flutterchina.club/chapter7/inherited_widget.html 2、小白初入门,看的就是《Flutter 实战》,写的真的太好了。今天看了一下InheritedWidget章节,然后在本地跑了一遍,发现一个问题,就是 child: _TestWidget(),//子widget中依赖ShareDataWidget,这个代码,我直接用 Text(ShareDataWidget .of(context) .data .toString()),就报错,说data没有setter。我不懂,还有,我也想在按钮的点击事件中,去看一下data的数据,也不行。请大佬详细一点解惑,感谢🙏

peng8934763 avatar Apr 28 '20 02:04 peng8934763

我想我知道原因了,我一直怀疑是我的context问题,所以,我在child:后面用了 Builder(builder:(cxt){ Text(ShareDataWidget.of(cxt).data.toString())}),问题解决了。

peng8934763 avatar Apr 28 '20 03:04 peng8934763

大佬用_TestWidget去接受这个data,也是为了告诉我们,依赖了inheritedWidget的子组件都会触发didChangeDependencies吧

peng8934763 avatar Apr 28 '20 03:04 peng8934763

我想我知道原因了,我一直怀疑是我的context问题,所以,我在child:后面用了 Builder(builder:(cxt){ Text(ShareDataWidget.of(cxt).data.toString())}),问题解决了。

请问这两种写法的context具体有啥区别?一个是父组件的上下文,一个是子组件的上下文?

scutlrr avatar May 17 '21 09:05 scutlrr