ChangeNotifier not updating Consumer

Issue

not sure why my ChangeNotifier isn’t working.

This is my Class:

class LoadingProv with ChangeNotifier {
  bool globalLoading;

  void setGlobalLoading(bool truefalse) {
    if (truefalse == true) {
      globalLoading = true;
    } else {
      globalLoading = false;
    }
    notifyListeners();
  }

  bool get getGlobalLoadingState {
    return globalLoading;
  }
}

This is my Multiprovider in main.dart:

MultiProvider(
      providers: [
        ChangeNotifierProvider<MapData>(create: (ctx) => MapData()),
        ChangeNotifierProvider<LoadingProv>(create: (ctx) => LoadingProv()),
      ],
      child: MaterialApp(

This is my code in the main.dart Widget build(BuildContext context):

Consumer<LoadingProv>(builder: (context, loadingState, child) {
                  return Text(loadingState.getGlobalLoadingState.toString());
                  }),

And this is how I call setGlobalLoading:

final loadingProv = LoadingProv();
 loadingProv.setGlobalLoading(true);

Unfortunately my loadingState.getGlobalLoadingState is always printed as false. But I can debug that it becomes actually true.

Solution

From my understanding, you are creating 2 LoadingProv object.
One is when initialising the Provider

ChangeNotifierProvider<LoadingProv>(create: (ctx) => LoadingProv()),

One is when some places you call

final loadingProv = LoadingProv();

So the one you updating is not the one inherit on the widget, then you cannot see the value updating the Consumer.

(1) if you want to keep create along with the create method, you should call setGlobalLoading via

Provider.of<LoadingProv>(context).setGlobalLoading(true);

(2) Or if you want to directly access the value like loadingProv.setGlobalLoading(true), you should initialise your provider like this

final loadingProv = LoadingProv(); 
MultiProvider(
      providers: [
        ChangeNotifierProvider<MapData>(create: (ctx) => MapData()),
        ChangeNotifierProvider<LoadingProv>.value(value: loadingProv),
      ],

Answered By – CbL

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.