【问题标题】:How should I adjust my widget tree in Flutter?我应该如何在 Flutter 中调整我的小部件树?
【发布时间】:2020-11-26 20:21:09
【问题描述】:

这是我的应用程序的小部件树。

deleteBtn 小部件中是一个按钮。如果我按下按钮,它应该将 false 值发送到 textVahybottomRect。这里有什么简单的方法吗?也许它可以用继承的小部件来完成,但我不能使用那个小部件......那么这里有什么简单的方法吗?

【问题讨论】:

    标签: android ios flutter dart flutter-layout


    【解决方案1】:

    我完全同意 David 使用 State Management 之类的 ProvidersBLoC。但是,如果您使用的是单页状态管理,那么您可以暂时离开它,因为它是高级主题。它还需要一些包导入,例如providersflutter_bloc 等。

    您可以做的是使用State Management 的简单版本,即ValueListenableBuilder class

    • 它检查您为它定义的值,即ValueNotifier 对象中的值,然后您将其传递给它。这是强制性的
    • 您包装小部件,它会在值更改时重建,在本例中为textVahybottomRect

    您将您的小部件包装在您的ValueListenableBuilder 中,用于textVahybottomRect

    现在,让我们用你想了解的方式来谈谈吧。

    ValueNotifier 的帮助下,我们将bool 值发送到树中的两个小部件

    // taking the initial value as true
    ValueNotifier<bool> _myBool = ValueNotifier<bool>(true);
    

    现在,我们包装两个小部件,它们仅受值更改的影响。

    请注意:不应包装其他小部件,无需使用bool更改

                ValueListenableBuilder(
                  // the value is myBool's value only
                  builder: (BuildContext context, bool value, Widget child) {
                    // This builder will only get called when _myBool
                    // is updated.
                    return Column(
                      children: <Widget>[
                        // whatever operation you wanna do based upon your value
                        // listen to value, since it has a param, it shows text with value
                        // if the value is false, else show you textVahy and bottomRect
                        if value ? textVahy : Text('$value'),
                        if value ? bottomRect : Text('$value')
                      ]
                    );
                  },
                  // passing ValueNotifier object to listen for any changes
                  valueListenable: _myBool
                )
    

    现在,当您想通过deleteBtn 更改_myBool 的值时,您只需通过setState() 进行操作

    RaisedButton(
       onPressed: (){
          // please note _myBool is the object of ValueNotifier, but _myBool.value has 
          // the right variable to store the predefined data
          setState(() => _myBool.value = false);
       },
       child: Text('Delete Me!!')
    )
    

    只要你点击按钮,值就会被发送到ValueListenableBuilder(),并根据bool,它会重建Widgets,将其包裹在其中。

    【讨论】:

      【解决方案2】:

      我建议使用某种状态管理,例如 BloC 或 Redux。在 Redux 的情况下,您可以将“dropDown”包装在 StoreProvider 中,它允许您处理来自各种小部件的各种事件。这些小部件需要包装在 StoreConnector 中。在您从一个连接器向 reducer 发送操作后,比如说游览“deleteBtn”,您可以定义另一个连接器的反应方式。看看例子here

      【讨论】:

        猜你喜欢
        • 2014-04-13
        • 1970-01-01
        • 2021-07-23
        • 2018-10-04
        • 1970-01-01
        • 2023-01-17
        • 2021-10-11
        • 2021-09-26
        • 2014-03-07
        相关资源
        最近更新 更多