ViralCode
ViralCode

Reputation: 189

flutter : how to persist a List<num> using shared preferences?

how to persist a List like List<num> = [2.5, 5, 7.5, 10] using SharedPreferences please ?

EDIT : how to convert stored data as String or List<String> to List ?

Upvotes: 8

Views: 10617

Answers (2)

Saed Nabil
Saed Nabil

Reputation: 6871

First, you need to convert your list of integers to a List of Strings, then you save it in shared preferences.

You do the opposite when loading.

This is a complete example:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
      body: new Center(
        child: new RaisedButton(
          onPressed: _save,
          child: new Text('Save my list of int'),
        ),
      ),
    ),
  ));
}

_save() async {

  List<int> myListOfIntegers = [1,2,3,4];
  List<String> myListOfStrings=  myListOfIntegers.map((i)=>i.toString()).toList();

  SharedPreferences prefs = await SharedPreferences.getInstance();
  List<String> myList = (prefs.getStringList('mylist') ?? List<String>()) ;
  List<int> myOriginaList = myList.map((i)=> int.parse(i)).toList();
  print('Your list  $myOriginaList');
  await prefs.setStringList('mylist', myListOfStrings);
}

Don't forget to add this to your pup spec.yaml file:

shared_preferences: ^0.4.3

Upvotes: 15

Rahul Mahadik
Rahul Mahadik

Reputation: 12291

As per documentation, there is no way to store list of numbers. But you implement it using:

 setStringList(String key, List<String> value) → Future<bool>

Saves a list of strings value to persistent storage in the background.

Implementation:

Future<bool> setStringList(String key, List<String> value) =>
    _setValue('StringList', key, value);

Another alternate way is like store whole list as a String.

Full documentation can be found in the Flutter packages repository.

Hope this will help you

Upvotes: 0

Related Questions