2

I'm working with SharedPreferences to make feature offline bookmark News . i can saved and fetching single value with this code :

Saved Value

void _testingSavePref(String judulBerita) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setString("tokenbookmark", judulBerita);
  }

Fetching Value

@override
  void initState() {
    super.initState();
    setState(() {
      _testingLoadPref();
    });
  }
_testingLoadPref() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
      tokenBookmark = pref.getString("tokenbookmark");
    });
  }

Everything is oke , but it's possible to saved and fetching multiple value with SharedPreferences ?

Example, i have 2 or more data, i want all data saved and not overwrite.

enter image description here Thank's

Zeffry Reynando
  • 3,445
  • 12
  • 49
  • 89
  • You might want to check the answers here https://stackoverflow.com/questions/61316208/how-to-save-listobject-to-sharedpreferences-flutter – Alexandre Jean Feb 10 '21 at 07:10
  • As well as this one https://stackoverflow.com/questions/55636980/can-i-put-list-into-sharedpreferences-in-flutter and this article https://medium.com/better-programming/flutter-how-to-save-objects-in-sharedpreferences-b7880d0ee2e4 – Alexandre Jean Feb 10 '21 at 07:16

2 Answers2

0

Updated Code:

For Saving Values

void _testingSavePref(List<String> judulBerita) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.setStringList("tokenbookmark", judulBerita); //judulBerita is a list of string now
  }

For Fetching Values

@override
  void initState() {
    super.initState();
    setState(() {
      _testingLoadPref();
    });
  }

_testingLoadPref() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
       final List<String>? tokenBookmark = pref.getStringList("tokenbookmark");
    });
  }

Now, You can get the data from tokenBookmark list by below code

for(String s in tokenBookmark){
  print(s);
}
Dev Hingu
  • 161
  • 2
-2

You shouldn't use SharedPreferences to save that kind of data.

Use a local sql or nosql database (sqflite / sembast).

Also don't call setState inside the initState method is wrong and unnecessary.

João Palma
  • 66
  • 11
  • Well can you elaborate? In my experience sqflite tends to have very obscure bugs on usage in flutter, the other packages are not lightweight and could be dropped any moment. Also I don't see any issue here to use Sharedpreferences as the data does not need to be secured imho and a JSON file to encode-decode should do just fine. – Alexandre Jean Feb 11 '21 at 10:06