简体   繁体   English

Flutter/Dart:我的小部件树中可以有多个带有 state 的小部件吗?

[英]Flutter/Dart: Can I have multiple widgets with state in my Widgets tree?

I was always wondering, why I have to "lift the state up" of some widget down in the tree, to reflect changes in the widget's UI.. Can't I just simply have multiple stateful Widgets?我一直在想,为什么我必须在树中“将 state 向上提升”,以反映小部件 UI 的变化。我不能简单地拥有多个有状态的小部件吗? and for example, import the lowest stateful widget down the tree into my top-level Widget, and from there could I not just call some method of my widget which triggers its setState() method and just updates that part in the DOM tree that is concerned with my widget?例如,将树中最低的有状态小部件导入到我的顶级小部件中,从那里我可以不只是调用我的小部件的一些方法来触发它的 setState() 方法,并且只是更新 DOM 树中的那个部分关心我的小部件?

And secondly, I would then have to move my properties and other important parts from the lower widget also up into my higher state widget, risking to clutter that class with unrelated functions and properties at some time, in my opinion, React solves that way better by just passing method callbacks down as it suits...其次,我必须将我的属性和其他重要部分从较低的小部件也移动到我的较高的 state 小部件中,冒着使 class 有时与不相关的功能和属性混乱的风险,在我看来,React 更好地解决了这种情况通过只传递适合的方法回调...

And is there always only one stateful widget in my Flutter app at the highest level?我的 Flutter 应用程序中是否总是只有一个有状态小部件处于最高级别?

  • Parents don't have access to child widgets/states, only the other way around.父母无权访问子小部件/状态,只能反过来。 So you can not "import the lowest stateful widget down the tree into my top-level Widget"所以你不能“将树下的最低状态小部件导入我的顶级小部件”

  • You only have to "lift the state up" when you want to share that state between different branches of the widget tree.当您想在小部件树的不同分支之间共享 state 时,您只需“抬起 state”。 Then the children can lookup the parent and access the shared state.然后孩子可以查找父母并访问共享的 state。

  • Don't be afraid of StatefulWidget - you can use as many as you need不要害怕StatefulWidget - 您可以根据需要使用任意数量

  • Research Flutter state management solutions which exist exactly for the purpose of keeping things separated (ChangeNotifier, Provider, BLOC, Redux, etc.)研究 Flutter state 管理解决方案,这些解决方案的存在正是为了将事物分开(ChangeNotifier、Provider、BLOC、Redux 等)

Can I have multiple widgets with state in my Widgets tree?我的小部件树中可以有多个带有 state 的小部件吗?

The answer is, yes you can create multiple StatefulWidget in your widget.答案是,是的,您可以在您的小部件中创建多个StatefulWidget You can also create a callback function from the lowest StatefulWidget with Function(yourcallback) .您还可以使用Function(yourcallback)从最低的StatefulWidget创建callback function 。 In my opinion, flutter also support component base model , and make as dynamic as possible to customize our own widget.在我看来,flutter 还支持组件库 model ,并尽可能动态地定制我们自己的小部件。

For example:例如:

child widget子小部件

child widget has it's state.子小部件的 state。

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)
        ],
      ),
    );
  }
}

Parent Widget父小部件

the parent get the callback from the child.父母从孩子那里得到回调。

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()),
            )
          ],
        ),
      ),
    );
  }
}

to change the child state from it's parent从它的父母改变孩子 state

you can use didUpdateWidget() here you can see the docs你可以在这里使用didUpdateWidget() 你可以看到文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM