2

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

关于如何.getWeather在初始负载上调用默认值,我有什么样的想法。该示例仅说明了在 Riverpod 文档中推荐context.read(..)的函数中的使用。onPressed(..)

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

4

2 回答 2

3

因为.getWeather是一个Future函数,所以其实可以在构造函数里面加入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?");
    }
  }
}
于 2021-02-09T07:44:49.460 回答
0

查看.family修饰符,您可以将数据传递给提供者返回的数据/状态。

https://riverpod.dev/docs/concepts/modifiers/family

使用参数监听状态:

final state = ref.watch(myProvider('my arg'));

创建提供者:

myProvider = StateNotifierProvider.family<String>((ref, arg) => "Hello $arg");

如果你打印状态,你会得到

print(state); //prints "Hello my arg"
于 2022-02-15T15:34:41.410 回答