【发布时间】:2021-08-04 16:33:15
【问题描述】:
我想在应用运行后获取整个应用的天气统计数据。
我的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
}
}
我的主文件:
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
}
还有更深的地方:
@override
Widget build(BuildContext context) {
return Consumer<WeatherStatsNotifier>(
builder: (context, value, child) {
return FutureBuilder<WeatherStats>(
future: value.stats,
builder: (context, snapshot) {
return _buildForSnapshot(snapshot);
},
);
},
);
}
最后我得到一个错误:
======== 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.
如何以正确的方式做到这一点?我可以在initState 或didChangeDependencies 中使用context 吗?
【问题讨论】:
标签: flutter dart flutter-provider