How to create a bool list in shared_preferences and store values ​there

Issue

required this.favorite,

I got the bool value from the previous page like this. Since I used the pageview, I want to store the value in the index like this and use it later.

  loadFavorite() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      favorite= prefs.getBoolList(_favoriteButton[index])!;
    });
  }


  void delete() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_favoriteButton[index], false);
    setState(() {
      favorite= prefs.getBool(_favoriteButton[index])!;
    });
  }

  void saved() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_favoriteButton[index], true);
    setState(() {
      favorite= prefs.getBool(_favoriteButton[index])!;
    });
  }

And I use the above code like this in the previous page. This is why I need a list. Without it I would have to create hundreds of pages.

  void loadFavorite() async{
    print(FavoriteButtons[0]);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      favorite[0] = prefs.getBool(_favoriteButton[0])!;

Is it possible to create a list from shared_preferences? And how can I store bool as a list?

Solution

You can hold bool list by this method:

List<bool> favorite = <bool>[];

Future<void> loadFavorite() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    favorite = (prefs.getStringList("userFavorite") ?? <bool>[]).map((value) => value == 'true').toList();
  });
}

Future<void> delete() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    favorite[index] = false;
  });
  await prefs.setStringList("userFavorite", favorite.map((value) => value.toString()).toList());
  setState(() {
    favorite = (prefs.getStringList("userFavorite") ?? <bool>[]).map((value) => value == 'true').toList();
  });
}

Future<void> saved() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    favorite[index] = true;
  });
  await prefs.setStringList("userFavorite", favorite.map((value) => value.toString()).toList());
  setState(() {
    favorite = (prefs.getStringList("userFavorite") ?? <bool>[]).map((value) => value == 'true').toList();
  });
}

Answered By – Røhäñ Dås

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *