简体   繁体   中英

How to use nested Consumers in Flutter?

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

The Consumer widget is a part of the Provider package, which is a popular solution for managing state in a Flutter application. The Consumer widget 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 nested Consumer , you simply wrap a Consumer widget inside another Consumer widget. 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 nested Consumers in 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 inner Consumer widget is accessing an instance of MyModel2 and the outer Consumer is accessing an instance of MyModel1 . The widget will be rebuilt whenever either MyModel1 or MyModel2 changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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