简体   繁体   English

Flutter:如何将 Riverpod 与 SharedPreference 和 List 结合使用<string>多页变量?</string>

[英]Flutter : How to use Riverpod with SharedPreference and List<String> Variable in multipage?

I've create List<String> favId = [];我创建List<String> favId = []; variable to store item's ID with SharedPreferences, so the favorited items ID didnt lost after I restart the application.使用 SharedPreferences 存储项目 ID 的变量,因此我重新启动应用程序后收藏的项目 ID 不会丢失。 And here is my SharedPreferences method and favorite IconButton in detailDoaPage.dart:这是我的 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();
                    }),
                  )

Beside that, I also want to show the favorited item's with ListView.builder in favPage.dart (another page).除此之外,我还想在 favPage.dart(另一页)中使用 ListView.builder 显示收藏的项目。 Of course I want get the favId from detailDoaPage.dart.当然,我想从 detailDoaPage.dart 中获取 favId。 How can I implement the provider/riverpod across this 2 pages?如何在这 2 个页面上实现提供程序/riverpod?

Here is the preview of my app:这是我的应用程序的预览:

在此处输入图像描述

Thank you:)谢谢:)

My recommended approach would be to create a StateNotifier that handles the state as well as the interactions with SharedPreferences.我推荐的方法是创建一个 StateNotifier 来处理 state 以及与 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);
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM