JoergP
JoergP

Reputation: 1559

ChangeNotifier not updating Consumer

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.

Upvotes: 0

Views: 2926

Answers (2)

Arman Zahmatkesh
Arman Zahmatkesh

Reputation: 83

you can use this code to read data when change it automatically refresh the Text widget

Text(context.watch<LoadingProv>().getGlobalLoadingState.toString());

on for calling the void you can use this

context.read<LoadingProv>().setGlobalLoading(true);

Upvotes: 0

CbL
CbL

Reputation: 824

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),
      ],

Upvotes: 1

Related Questions