Home > Enterprise >  Saving Local Data for a list on Flutter
Saving Local Data for a list on Flutter

Time:05-18

I have an app that plays a sound. There is a list of sounds and I show that to an listview. So user can click a listtile and plays a sound. And I added a "Favourite" section. And it works fine. But when user closes the app it goes away. I tried to use SharedPrefences but I couldnt manage to do it. Because I need to save the whole list and I dont know how.

When I close the app, all my 'favourite' list goes away.

I will just share all the codes for better understanding:

Main page with 2 favourite sound

Favourite Page

After the restart

CodePudding user response:

Since the list of saved songs is a list of Strings you can use setStringList() method from SharedPrefences. When you want to save the list, use:

final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('savedSounds', savedSounds);

Then when the application starts you load the songs by using:

final prefs = await SharedPreferences.getInstance();
savedSounds = prefs.getStringList('savedSounds') ?? [];

Then you can use a for-loop to also get the saved indexes, although I would recommend you to try only using one list of the saved songs.

for(int i = 0; i < savedSounds.length; i  ){
      if(soundList[i] == savedSounds[i]){
        savedIndex.add(i.toString());
      }
    }

CodePudding user response:

You can use the SQFlite package to store your List items locally. Here is the package: https://pub.dev/packages/sqflite

  • Related