如何在另一个页面(收藏夹页面)的另一个列表中的共享首选项中显示保存的列表?

How to display a saved list in Shared preferences in another list in another page(Favorite page)?

Hello community, I'm new to the Flutter world and mobile app development and struggling with How to display a saved list in Shared preferences in another list in another page(Favorite page

The favorite button to save the list in 共享首选项:


        Padding(
                      padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                      child: FlatButton(
                        child: Icon(
                          Icons.favorite,
                          color: Colors.green,
                          size: 25,
                        ),
                        onPressed: () async {
                          SharedPreferences prefs =
                              await SharedPreferences.getInstance();

                          Article savedArticle = Article(
                              source: widget.list[i].source,
                              author: widget.list[i].author,
                              title: widget.list[i].title,
                              description: widget.list[i].description,
                              url: widget.list[i].url,
                              urlToImage: widget.list[i].urlToImage,
                              publishedAt: widget.list[i].publishedAt,
                              content: widget.list[i].content);

                          String json = jsonEncode(savedArticle);

                          //  print('saved... $json');
                          list.add(json);
                          prefs.setStringList('News', list);
                          print("shared..." +
                              prefs.getStringList('News').length.toString());
                        },
                      ),
                    ),

This is a screenshot of the saved list in shared pref displayed in the console:

This is a screenshot of the list with the favorite button from where I saved the articles in the SharedPref by clicking the favorite button:

My goal is to display the saved list in the shared preferences in another page (favorite articles page) in a list but without favorite button. Could any one help me PLEASE ? Thank you.

在另一个页面上,您必须获取共享首选项实例。

final sharedPreferences = await SharedPreferences.getInstange();

然后您可以通过sharedPreferences.getStringList('News')获取您的列表;并通过 json.decoder;

转换为 json

如果您想创建文章 class 的实例,那么您可以在其中实现一个方法,该方法 return 来自 json 的 class 的新实例]. 例如:

class Article {
  factory Article fromJson(Map<String, dynamic> json) {
    return Article(id: json['id'], ...);
  }
}