I recognize FutureProvider
can be used when a model will be given by a Future
. It is needed to initialize the model by its init() async
method, so I tried FutureProvider
. However FutureProvider
didn't give an instance of the model. It had given null
.
Additionally while using ChangeNotifierProvider
successfully updates UI, FutureProvider
seems to not update UI when the notifyListeners()
is called. Consumer
gives same result. Is there anything to be fixed? Thank you.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class MyModel extends ChangeNotifier {
int _point = 0;
int get point => _point;
set point(int value) {
if (_point != value) {
_point = value;
notifyListeners();
}
}
Future<void> init() async { /* Use await doSomething(); */ }
}
void main() => runApp(
FutureProvider<MyModel>(
create: (context) async {
final model = MyModel();
await model.init();
return Future.value(model);
},
lazy: false,
updateShouldNotify: (_, __) => true,
child: MyHomePage(),
),
);
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final model = Provider.of<MyModel>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Center(
child: Text(
'${model.point}',
style: Theme.of(context).textTheme.display1,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
model.point++;
},
child: Icon(Icons.add),
),
),
);
}
}