42

I can't wrap my head around using multiple consumers for a single widget with provider? Suppose my widget is CurvedNavigationBar and I have 4 items in that widget. I also have 4 different classes that extend ChangeNotifier and are responsible for each item in CurvedNavigationBar.

How can I listen to those 4 change notifiers in a single widget? I looked at the documentation and could not found such an example.. is this even possible? I found that Consumer has a builder method, so that means you can build a widget only once/and listen to it once.

Should I rather have a single class that extends ChangeNotifier and then update values in that widget and uses only a single Consumer to listen for updated values?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Viktor Vostrikov
  • 1,322
  • 3
  • 19
  • 36

3 Answers3

88

There are some other Consumer widgets. Consumer2, Consumer3, Consumer4 till Consumer6. If you want to listen 4 ChangeNotifier you can use Consumer4

Consumer4(
  builder: (context, changeNotifier1, changeNotifier2, changeNotifier3, changeNotifier4, child) {
    // your widget
  }
)
Selim Kundakçıoğlu
  • 1,986
  • 10
  • 20
45

Yes you can add up to 6 consumers and will be as following

    Consumer2<AuthProvider, StorageProvider>(
    builder: (context, authProvider, storageProvider, child) {

    }
    )
Islam Emam
  • 678
  • 5
  • 11
3

There is another way to get access to your providers: Provider.of<SomeProvider>(context):

Widget build(BuildContext context) {
  final authProvider = Provider.of<AuthProvider>(context);
  final apiProvider = Provider.of<ApiProvider>(context);
  final storageProvider = Provider.of<StorageProvider>(context);

  // Do your usual stuff without wrapping it into Consumer,
  // just pass providers directly to your targets.
  return MyAwesomeWidget(
    authProvider,
    apiProvider,
    storageProvider,
  );
}
Aux
  • 440
  • 3
  • 10
  • I had same mistake like you (include using Builder Widget), please test it, you'll see it work but it has performance issue, the app will slow down at least 33% for 3 providers. I have to vote it down. – SLyHuy Dec 25 '21 at 12:09
  • If you are passing objects fetched from provider into a widget, then you should just get rid of all the parameters and call Provider.of<...> within the widget where it's needed to minimize what is rebuilt. – Jeff Neet Feb 19 '23 at 01:52