问题描述
我正在关注有关如何使用 RiverPod 和 StateNotifier 管理状态的 Resocoder tutorial。
关于如何在初始加载时使用默认值调用 .getWeather
是一种什么样的旅行。该示例仅说明在 context.read(..)
函数中使用 onpressed(..)
,这是 Riverpod 文档中推荐的做法。
但是,您实际上如何在加载时进行调用,因为这意味着在构建方法中调用 context.read
,这是非常不鼓励的。 (在本 section 的最后一部分中提到)
解决方法
因为 .getWeather
是一个 Future 函数,你实际上可以在 WeatherNotifier
的构造函数中添加 Future 初始化并让它自己更新状态。
final weatherNotifierProvider = StateNotifierProvider(
(ref) => WeatherNotifier(ref.watch(weatherRepositoryProvider)),);
class WeatherNotifier extends StateNotifier<WeatherState> {
final WeatherRepository _weatherRepository;
WeatherNotifier(this._weatherRepository) : super(WeatherInitial()){
getWeather('some city name'); // add here
}
Future<void> getWeather(String cityName) async {
try {
state = WeatherLoading();
final weather = await _weatherRepository.fetchWeather(cityName);
state = WeatherLoaded(weather);
} on NetworkException {
state = WeatherError("Couldn't fetch weather. Is the device online?");
}
}
}