Search code examples
flutterdartproviderstate-managementflutter-change-notifier

Accessing data from a main Provider in a sub-Provider in Flutter (Provider refactoring)


I am relatively new to Flutter and I am trying to split my Provider into one main Provider, which holds all my data, and multiple sub-Providers that extend it. These sub-Providers are responsible for manipulating the data and providing some getters as well.

I tried using the extend keyword on the main Provider to create the sub-Providers. Everything seemed to be fine, but I was not able to access the data from the sub-Providers.

In the example code below, the load() function loads data into mainData on startup, and the data is then accessible from the MainProvider with no issues. However, if I try to access the data from the SubProvider, I get an error because mainData is null (or empty, it doesn't matter), so it seems not to see any change to the state of the MainProvider.

What am I doing wrong here, and is this the best way to refactor a Provider or am I missing something?

class MainProvider extends ChangeNotifier {
  late List<String> mainData;

  void load() {
    // loads data from shared preferences into mainData
  }
}

class SubProvider extends MainProvider {
  void add() {}
  void remove() {}
  // ...
  void printLength() {
    debugPrint(mainData.length.toString()); //error: e.g. mainData has not been initialized
  }
} 

I tried googling the issue with no result...


Solution

  • It's my rough guess, because I can't see the rest of your code, but you need to call load on each instance of the SubProvider class. SubProvider shares MainProvider class/interface, not its object.