我一直在想,为什么我必须“提升”树中某个小部件的状态,以反映小部件 UI 中的变化。 我不能只是简单地拥有多个有状态的小部件吗?例如,将树中最低的有状态小部件导入到我的顶级小部件中,从那里我可以不只是调用我的小部件的某些方法来触发它的 setState() 方法,而只是更新 DOM 树中的那部分关心我的小部件?
其次,我将不得不将我的属性和其他重要部分从较低的小部件也移到我的较高状态的小部件中,冒着在某个时间用不相关的功能和属性将该类弄乱的风险,在我看来,React 解决了通过只传递适合的方法回调来更好地...
我的 Flutter 应用程序中是否总是只有一个最高级别的有状态小部件?
答案 0 :(得分:1)
父母无权访问子小部件/状态,只能反过来。所以你不能“将树下最低的有状态小部件导入我的顶级小部件”
当您想在小部件树的不同分支之间共享该状态时,您只需“提升状态”。然后子节点可以查找父节点并访问共享状态。
不要害怕 StatefulWidget
- 您可以根据需要使用任意数量
研究 Flutter 状态管理解决方案,这些解决方案的存在正是为了将事物分开(ChangeNotifier、Provider、BLOC、Redux 等)
答案 1 :(得分:0)
我的小部件树中可以有多个带状态的小部件吗?
答案是,是的,您可以在您的小部件中创建多个 StatefulWidget
。您还可以使用 callback
从最低的 StatefulWidget
创建一个 Function(yourcallback)
函数。在我看来,flutter 也支持组件基础模型,并且尽可能动态地自定义我们自己的小部件。
例如:
子小部件有它的状态。
class Child extends StatefulWidget {
final int counter;
final Function(int childCounter) callback; //here is your callback
const Child({
Key key,
this.counter,
this.callback,
}) : super(key: key);
@override
_ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
String _childState = '';
@override
Widget build(BuildContext context) {
return Container(
color: Colors.green[400],
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Child"),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.exposure_minus_1_rounded),
onPressed: () {
this.widget.callback(this.widget.counter - 1); //here is your callback
setState(() {
_childState = "minus one";
});
}),
IconButton(
icon: Icon(Icons.plus_one_rounded),
onPressed: () {
this.widget.callback(this.widget.counter + 1); //here is your callback
setState(() {
_childState = "plus one";
});
})
],
),
Text(_childState)
],
),
);
}
}
父级从子级获得回调。
class Parent extends StatefulWidget {
@override
_ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Multiple State"),
),
body: Container(
child: Column(
children: [
Child(
counter: _counter,
callback: (childCounter) { //here is callback from the child
print(childCounter);
setState(() {
_counter = childCounter;
});
},
),
Text("Parent"),
Center(
child: Text(_counter.toString()),
)
],
),
),
);
}
}
您可以使用 didUpdateWidget()
here you can see the docs