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 ?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With