我正在try 使用Riverpod,特别是使用riverpod_generator,由于没有太多的文档围绕这一点,我很难建立一个项目来利用所有这些.我想用shared_preferences包创建一个提供程序,以便我可以全局访问该提供程序.似乎通过使用这个生成器,你可以避免知道你需要哪个提供者(状态,future 等).我必须说这是一件很好的事情,但我不太确定我是否理解了整个范围.
首先,类将成为全局共享的子系统提供者(尽管设置不正确,因此请求帮助)
@riverpod // annotation for the riverpod_generator
class SharePrefNotifier extends _$SharePrefNotifier{
@override
SharedPreferences build() {
return _sharedPreferences;
}
// Obtain shared preferences but this is not correct although the compiler asks to be late
late SharedPreferences _sharedPreferences;
int? get getPin =>
_sharedPreferences.getInt(_pinKey);
Future<void> setPin(int? pinNumber) async => await _sharedPreferences.setInt(_pinKey, pinNumber);
Future<void> removePin() async => await _sharedPreferences.remove(_pinKey);
Future<void> deleteAll() async => await _sharedPreferences.clear();
}
当我修复了共享数据库提供程序的设置时,我希望在另一个提供程序中访问它:
@riverpod
class SettiingPinNotifier extends _$SettiingPinNotifier {
// referencing the shared_pred notifier on the top of the scope if possible so I can reference it anywhere in this provider if I have multiple methods
final sharedPrefProvider = ref.read(sharedPrefProvider.notifer);
@override
SomeDataState build() {
return const SomeDataState();
}
void setUpAPin(int? number) {
sharedPrefProvider.setPin(number); // referencing the shared pref provider and setup a pin number
state = state.copyWith(pin: number); // adding it to the state so I can change the UI accordingly
}
}
除了使用riverpod_generator/riverpod_annotation之外,这里最好的方法是什么?提前感谢你的帮助.