Flutter:如何将Riverpod与SharedPreference和List< String>一起使用多页变量? [英] Flutter : How to use Riverpod with SharedPreference and List<String> Variable in multipage?

查看:94
本文介绍了Flutter:如何将Riverpod与SharedPreference和List< String>一起使用多页变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了 List< String>favId = []; 变量用于存储具有SharedPreferences的商品ID,因此在重新启动应用程序后,收藏的商品ID不会丢失.这是我的SharedPreferences方法和最喜欢的IconButton的详细信息.

I've create List<String> favId = []; variable to store item's ID with SharedPreferences, so the favorited items ID didnt lost after I restart the application. And here is my SharedPreferences method and favorite IconButton in detailDoaPage.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.如何在这两个页面中实施提供者/河流脚架?

Beside that, I also want to show the favorited item's with ListView.builder in favPage.dart (another page). Of course I want get the favId from detailDoaPage.dart. How can I implement the provider/riverpod across this 2 pages?

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

Here is the preview of my app :

谢谢:)

推荐答案

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

My recommended approach would be to create a StateNotifier that handles the state as well as the interactions with SharedPreferences. The following simplifies the logic in your widgets as well.

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);
  }
}

用法:

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()),
    );
  }
}

这篇关于Flutter:如何将Riverpod与SharedPreference和List&lt; String&gt;一起使用多页变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆