我想使用 SharedPreferences.getInstance() 方法在我的一个数据源中注入一个 SharedPreferences 实例,但我遇到了困难,因为 getInstance() 返回一个 Future。这是我的提供程序文件:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shopping_list/features/shopping_list/data/datasources/item_local_data_source.dart';
import 'package:shopping_list/features/shopping_list/data/repositories/item_repository_impl.dart';
import 'package:shopping_list/features/shopping_list/domain/repositories/item_repository.dart';
import 'item_list_state.dart';
import 'package:shopping_list/core/usecases/usecases.dart';
import 'package:shopping_list/features/shopping_list/domain/usecases/cache_items_list.dart';
import 'package:shopping_list/features/shopping_list/domain/usecases/get_items_list.dart';
import 'package:shopping_list/features/shopping_list/presentation/logic/item_list/item_list_state.dart';
import 'package:shopping_list/features/shopping_list/domain/entities/ingredient.dart';
part 'item_list_state_notifier.dart';
final sharedPreferencesProvider = Provider(
(ref) => SharedPreferences.getInstance()
);
final _localDataSourceProvider = Provider<ItemLocalDataSource>(
(ref) =>
ItemLocalDataSourceImpl(sharedPreferences: ref.watch(sharedPreferencesProvider))
);
final _itemRepositoryProvider = Provider<ItemRepository>(
(ref) => ItemRepositoryImpl(localDataSource: ref.watch(_localDataSourceProvider))
);
final _getItemsListProvider =
Provider<GetItemsList>((ref) => GetItemsList(ref.watch(_itemRepositoryProvider)));
final _cacheItemsListProvider =
Provider<CacheItemsList>(
(ref) => CacheItemsList(ref.watch(_itemRepositoryProvider))
);
final itemListNotifierProvider =
StateNotifierProvider<ItemListNotifier, ItemListState>((ref) =>
ItemListNotifier(
getItemsList: ref.watch(_getItemsListProvider),
cacheItemsList: ref.watch(_cacheItemsListProvider)));
我尝试覆盖 ProviderScope 中的 sharedPreferencesProvider,但没有帮助。
使用 Riverpod 实例化 SharedPreferences 的最佳方法是什么?
答案 0 :(得分:0)
您可以为此使用 FutureProvider
,例如:
final configProvider = FutureProvider<Configuration>((ref) async {
final content = json.decode(
await rootBundle.loadString('assets/configurations.json'),
) as Map<String, Object?>;
return Configuration.fromJson(content);
});
所以在你的情况下,它会是这样的:
final configProvider = FutureProvider<SharedPreferences>((ref) async {
final prefs = await SharedPreferences.getInstance();
return prefs;
});
更多信息:https://pub.dev/documentation/riverpod/latest/riverpod/FutureProvider-class.html