How to use Futures inside ChangeNotifier?

旧时模样 提交于 2020-05-31 05:45:46

问题


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();
  }
}

回答1:


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.



来源:https://stackoverflow.com/questions/56937162/how-to-use-futures-inside-changenotifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!