问题
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