Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 479
ViralCode Avatar asked Nov 24 '18 07:11

ViralCode


People also ask

Can we store list in shared preferences flutter?

The data stored in SharedPreferences can be edited and deleted. SharedPreferences stores the data in a key-value pair. To use SharedPreferences in Flutter, a plugin called shared_preferences enables us to store data. The plugin wraps NSUserDefaults on iOS and SharedPreferences on Android.

How do I save a list in shared preferences?

apply() − It going to commit back changes from editor to shared preference. remove(String key) − It going to remove key and vales from shared preference use key. Put() − It going to put key and values to shared preference xml.

How do I store list values in SharedPreferences in flutter?

First, in order to use the SharedPreferences , we have to use Flutter's plugin for it. To do so, make sure dependencies in your pubspec. yaml file looks similar to this: To save something in SharedPreferences , we must provide a value that we want to save and a key that identifies it.


1 Answers

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
like image 141
Saed Nabil Avatar answered Sep 28 '22 18:09

Saed Nabil