使用 RiverPod 和 StateNotifiers 在加载时调用函数

Geo*_*ent 3 flutter riverpod

我正在关注Resocoder 教程,了解如何使用 RiverPod 和 StateNotifier 管理状态。

我的问题是如何.getWeather在初始加载时调用默认值。该示例仅说明了在 Riverpod 文档中推荐的函数context.read(..)中的使用。onPressed(..)

但是,您实际上如何在加载时进行调用,因为这意味着调用context.read构建方法,这是非常不鼓励的。(本节最后一部分提到)

yel*_*ray 5

因为.getWeather是一个 Future 函数,所以您实际上可以在 的构造函数中添加未来的初始化WeatherNotifier,并让它自己更新状态。

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?");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)