我正在尝试从Flutter中的不同小部件更改状态 . 例如,在以下示例中,我在几秒钟后设置状态 .
这是代码:
class _MyAppState extends State<MyApp> {
int number = 1;
@override
void initState() {
super.initState();
new Future.delayed(new Duration(seconds: 5)).then((_) {
this.setState(() => number = 2);
print("Changed");
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new FlatButton(
color: Colors.blue,
child: new Text("Next Page"),
onPressed: () {
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context) => new StatefulBuilder(builder: (BuildContext context, setState) =>new MySecondPage(number))
));
},
),
),
);
}
}
我尝试使用 InheritedWidget
,但是它试图做到这一点(上面的代码是我想要实现的简化) .
有关实现这一目标的最佳方法的任何想法都在Flutter中?
1 回答
尽可能避免这种情况 . 它使这些小部件相互依赖,并且可以使事情在长期内更难维护 .
你可以做的是让两个小部件共享一个共同的Listenable或类似的东西,如Stream . 然后,小部件通过提交事件相互交互 .
为了便于编写,您还可以将
Listenable
/Stream
分别与ValueListenableBuilder和StreamBuilder结合使用,它们都可以为您执行监听/更新部分 .Listenable
的快速示例 .请注意这里我们如何在执行
number.value++
时自动更新UI,而无需调用setState
.