0

While the entire way I'm managing state in my flutter app is probably somewhat nonsensical, so far my use of Providers/ChangeNotifiers/Consumers has at least somewhat worked. However, I'm now stuck with one of them.

In a class of mine, which happens to be a singleton, I have a MapChangeNotifier member (Essentially a Map, but the Map is also a ChangeNotifier and thus calls notifyListeners() when something gets changed.)

As I'm using this map to construct a list dynamically somewhere further down in my widget tree, I need to wrap a Provider around it and use a Consumer when building my list, so that it updates itself automatically. Since I kind of dislike this way of handling state I initially thought of maybe just making the Map a static member, and then simply call the rebuild function of the list widget manually whenever I update the map. But that was ugly as well so I let it be.

My Map looks as follows:

MapChangeNotifier<String, String> queries = MapChangeNotifier<String, String>();

In any case, I now have the following structure at the very top level of my App:

return MultiProvider(providers: [
  ChangeNotifierProvider(create: (_)=>MySingleton().queries)
], child: RestOfMyApp())

Somewhere way further down, I push a Route onto the Navigator which contains the List that should Consume the map. I initially wanted to push a Provider onto the Navigator stack here so that I don't need to have it in my "global" scope, but since that didn't work I thought I'd just put it there at first. I then consume it as such:

return Consumer<MapChangeNotifier<String, String>>(
  builder: (context, queries, child) => Scaffold(
    ...
    // somewhere down in the list widget under my scaffold, I use "queries"
    ...
  )
);

At the first line, where I use the Consumer, I get the error that the Provider was not found. Which, imo, makes no sense... What am I missing?

Fly
  • 810
  • 2
  • 9
  • 28

1 Answers1

0

Try this


return MultiProvider(providers: [
  ChangeNotifierProvider(create: (_)=>MapChangeNotifier())
], child: RestOfMyApp())

Mahi
  • 1,297
  • 1
  • 14
  • 28
  • But that would create a new Map. I want to use an existing map, as I have some methods in my singleton that load its content to and from storage. And technically it shouldn't make a difference, since by creating a new one, I'm also just storing an instance, so whether I specify an existing instance or a new one shouldnt matter, right? – Fly May 22 '22 at 11:50
  • I don't understand actually with this small piece of code. But based on the error, when you try to access the provider it doesn't get one. So that's why I suggest the above code. – Mahi May 22 '22 at 12:27