I want to fetch data about weather stats for entire app once after app is runned.
My ChangeNotifier:
class WeatherStatsNotifier extends ChangeNotifier {
WeatherService weatherService;
Future<WeatherStats> _stats;
WeatherStatsNotifier({this.weatherService});
Future<WeatherStats> get stats => _stats;
void refreshStats() {
_stats = weatherService.fetchWeatherStats();
notifyListeners(); // it works when I remove this line
}
}
My main file:
final WeatherService weatherService = new WeatherService();
void main() => runApp(ChangeNotifierProvider(
create: (context) => WeatherStatsNotifier(weatherService: weatherService),
child: App()));
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
@override
void didChangeDependencies() {
Provider.of<WeatherStatsNotifier>(context, listen: false).refreshStats();
super.didChangeDependencies();
}
//... build method
}
and somewhere deeper:
@override
Widget build(BuildContext context) {
return Consumer<WeatherStatsNotifier>(
builder: (context, value, child) {
return FutureBuilder<WeatherStats>(
future: value.stats,
builder: (context, snapshot) {
return _buildForSnapshot(snapshot);
},
);
},
);
}
Finally I get an error:
======== Exception caught by widgets library =======================================================
The following assertion was thrown building ChangeNotifierProvider<WeatherStatsNotifier>(message: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4195 pos 12: '!_dirty': is not true.\nSee also: https://flutter.dev/docs/testing/errors, dirty, renderObject: RenderErrorBox#c84e8 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4195 pos 12: '!_dirty': is not true.
How to do it in correct way? Am I able to use context inside initState or didChangeDependencies or not?