【问题标题】:How to use nested Consumers in Flutter?How to use nested Consumers in Flutter?
【发布时间】:2022-12-27 15:02:07
【问题描述】:

I need to access two different view model in one page in Flutter.
How to use nested Consumers in Flutter, Will they effect each other?

How can I use it in this code for example?

class CounterDisplay extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<CounterModel>(
      builder: (context, counterModel, child) {
        return Text('${counterModel.count}');
      },
    );
  }
}

【问题讨论】:

    标签: flutter nested provider consumer


    【解决方案1】:

    TheConsumerwidget is a part of theProviderpackage, which is a popular solution for managing state in a Flutter application. TheConsumerwidget allows you to access a specific piece of the app's state within a widget tree, and rebuild a widget whenever that piece of state changes.

    To use a nestedConsumer, you simply wrap aConsumerwidget inside anotherConsumerwidget. This allows you to access multiple pieces of state within a single widget tree, and rebuild the widget whenever any of those pieces of state change.

    Here's an example of how you might use nestedConsumersin a Flutter widget:

    Consumer<MyModel1>(
        builder: (context, myModel1, child) {
            return Consumer<MyModel2>(
                builder: (context, myModel2, child) {
                    return Text(myModel1.someValue + myModel2.someValue);
                    },
            );
        },
    )
    

    In this example, the innerConsumerwidget is accessing an instance ofMyModel2and the outerConsumeris accessing an instance ofMyModel1. The widget will be rebuilt whenever eitherMyModel1orMyModel2changes.

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 1970-01-01
      • 2022-12-02
      • 2022-12-28
      • 2022-12-27
      • 2022-12-02
      • 2022-12-02
      • 2022-12-27
      • 2020-07-21
      相关资源
      最近更新 更多