4

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();
  }
}
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
UVic
  • 1,671
  • 3
  • 14
  • 21

1 Answers1

13

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.

Erol Asan
  • 378
  • 2
  • 12
  • Will creating a refetch function as I have done in the edited question above valid....??? – UVic Jul 08 '19 at 16:34
  • Added ```notifyListeners();``` at the end of ```loadData();``` works fine now – UVic Jul 08 '19 at 17:14
  • you already have notifyListeners(); in the setter for myValue, you shouldn't need again in fetching methods – Erol Asan Jul 09 '19 at 08:08