Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Futures inside ChangeNotifier?

I have an sqlite database from which I read data. I also have a long widget tree. So after a bit of research I found the provider Flutter package. But I can't figure out how to use Futures inside the class extending ChangeNotifier or How to use it anywhere in my widget tree?

class MyProvider with ChangeNotifier {
  dynamic _myValue;

  dynamic get myValue => _myValue;

  set myValue(dynamic newValue) {
    _myValue = newValue;
    notifyListeners();
  }

  MyProvider(){
    loadValue();
  }

  Future<void> loadValue async {
    myValue = await db.instance().getValue();
  }

  Future<void> refetch async {
    myValue = await db.instance().newValue();
    notifyListeners();
  }
}
like image 389
UVic Avatar asked Sep 03 '25 15:09

UVic


1 Answers

I suggest you go and understand how Futures and the Provider package works first. You can either wait for the Future to finish directly in your widget tree using the .then() method or you can handle this in the provider like this:

class MyProvider with ChangeNotifier {
  dynamic _myValue;

  dynamic get myValue => _myValue;

  set myValue(dynamic newValue) {
    _myValue = newValue;
    notifyListeners();
  }

  MyProvider(){
    loadValue();
  }

  Future<void> loadValue async {
   myValue = await db.instance().getValue();
  }
}

Then in your widget tree:

build(context) {
  return ChangeNotifierProvider.value(
    value: MyProvider(),
    child: Consumer<MyProvider>(builder:
      (BuildContext context, MyProvider provider, Widget child) {
       if(provider.myValue == null) {
         return Center(
            child: CircularProgressIndicator(),
         );
       } else {
          return Container(
            child: Text(provider.myValue);
          );
       }
    }
  );
}

That is just one way of doing it, but there are plenty of other ways to handle this.

like image 76
Erol Asan Avatar answered Sep 05 '25 14:09

Erol Asan