Ad

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 inShared Preferences :


        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.

Ad

Answer

On another page you have to get shared preferences instance.

final sharedPreferences = await SharedPreferences.getInstange();

Then you can get your list by sharedPreferences.getStringList('News'); and convert to json by json.decoder;

If you want to make an instance of your Article class then you could implement a method inside of that that would return new instance of the class from json. For example:

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