颤动:如何保持List< num>使用共享的首选项? [英] flutter : how to persist a List<num> using shared preferences?
本文介绍了颤动:如何保持List< num>使用共享的首选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何持久保存 List< num>之类的列表= [2.5,5,7.5,10]
使用 SharedPreferences
请吗?
how to persist a List like List<num> = [2.5, 5, 7.5, 10]
using SharedPreferences
please ?
编辑:如何将存储的数据转换为 String
或 List< String>
到列表?
EDIT : how to convert stored data as String
or List<String>
to List ?
推荐答案
首先,您需要将整数列表转换为字符串列表
,然后将其保存在共享首选项中。
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.
这是一个完整的示例:
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);
}
别忘了将此添加到您的pup spec.yaml文件: / p>
Don't forget to add this to your pup spec.yaml file:
shared_preferences: ^0.4.3
这篇关于颤动:如何保持List< num>使用共享的首选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文