Flutter:如何在多页面中将 Riverpod 与 SharedPreference 和 List 变量一起使用?

2023-12-12

我已经创建了List<String> favId = [];变量来使用 SharedPreferences 存储项目的 ID,这样在我重新启动应用程序后,收藏的项目 ID 就不会丢失。这是我的 SharedPreferences 方法和最喜欢的 IconButton 的详细信息DoaPage.dart :

...
static List<String> favId = [];

  getData() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
      favId = pref.getStringList("id") ?? [];
    });
  }

  void initState() {
    super.initState();
    getIds();
  }

  getIds() async {
    favId = getData();
  }

  void saveData() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setStringList("id", favId);
  }
...
IconButton(
                    icon: Icon(
                      favId.contains(doa.id.toString())
                          ? Icons.favorite
                          : Icons.favorite_border,
                      color: favId.contains(doa.id.toString())
                          ? Colors.red
                          : Colors.grey,
                    ),
                    onPressed: () => setState(() {
                      doa.fav = !doa.fav;
                      if (favId.contains(doa.id.toString())) {
                        favId.removeWhere(
                            (element) => element == doa.id.toString());
                      } else {
                        favId.add(doa.id.toString());
                      }
                      saveData();
                      favId.sort();
                    }),
                  )

除此之外,我还想在 favPage.dart(另一个页面)中使用 ListView.builder 显示收藏的项目。当然,我想从detailDoaPage.dart中获取favId。我如何在这两个页面上实现provider/riverpod?

这是我的应用程序的预览:

enter image description here

谢谢 :)


我推荐的方法是创建一个 StateNotifier 来处理状态以及与 SharedPreferences 的交互。下面也简化了小部件中的逻辑。

final sharedPrefs =
    FutureProvider<SharedPreferences>((_) async => await SharedPreferences.getInstance());

class FavoriteIds extends StateNotifier<List<String>> {
  FavoriteIds(this.pref) : super(pref?.getStringList("id") ?? []);

  static final provider = StateNotifierProvider<FavoriteIds, List<String>>((ref) {
    final pref = ref.watch(sharedPrefs).maybeWhen(
          data: (value) => value,
          orElse: () => null,
        );
    return FavoriteIds(pref);
  });

  final SharedPreferences? pref;

  void toggle(String favoriteId) {
    if (state.contains(favoriteId)) {
      state = state.where((id) => id != favoriteId).toList();
    } else {
      state = [...state, favoriteId];
    }
    // Throw here since for some reason SharedPreferences could not be retrieved
    pref!.setStringList("id", state);
  }
}

Usage:

class DoaWidget extends ConsumerWidget {
  const DoaWidget({Key? key, required this.doa}) : super(key: key);

  final Doa doa;

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final favoriteIds = watch(FavoriteIds.provider);

    return IconButton(
      icon: favoriteIds.contains('') ? Icon(Icons.favorite) : Icon(Icons.favorite_border),
      color: favoriteIds.contains('') ? Colors.red : Colors.grey,
      onPressed: () => context.read(FavoriteIds.provider.notifier).toggle(doa.id.toString()),
    );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter:如何在多页面中将 Riverpod 与 SharedPreference 和 List 变量一起使用? 的相关文章

随机推荐