我试图了解如何在Flutter中存储地图列表,显示它,以及以后按索引从中添加和减去。我开始使用jsonEncode / Decode将整个内容另存为String,但是我认为这不是正确的方法,而且由于编码后不再是List<Map<String, dynamic>>
,所以我无法再添加回它。任何帮助将不胜感激。
class Favs extends StatefulWidget {
@override
_Favs createState() => _Favs();
}
class _Favs extends State<Favs> {
SharedPreferences sharedPreferences;
List<Map<String, dynamic>> _favList=[{id: 1, bookTxt: Here is my text., bookAuthor: Isaiah},{id: 2, bookTxt: Here is my text again., bookAuthor: Matt}];
List<dynamic> _newList = [];
@override
void initState(){
super.initState();
getSavedInfo();
}
getSavedInfo() async {
sharedPreferences = await SharedPreferences.getInstance();
var myFavList = sharedPreferences.getString('myFavList');
if (myFavList != null){
var myFavListCheck = jsonDecode(myFavList);
_newList = myFavListCheck;
}
}
_saveToList(List<Map<String, dynamic>> _favList) async {
var s = json.encode(_favList);
sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString('myFavList', s);
print('DONE WITH _saveToList');
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text('ListView Builder'),),
body: ListView.builder(
itemCount: _newList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Container(
height: 80.0,
child: Center(
child: Text(_newList[index]['bookTxt'])
)
),
);
},
),
floatingActionButton: _addMoreButton(),
);
}
_addMoreButton(){
_favList.add({'id': '3','bookTxt': 'Here is 3rd text','bookAuthor': 'Johnny'});
_saveToList(_favList);
}
}
答案 0 :(得分:1)
解码和编码是写入方式。为什么您不尝试使用flutter_secure_storage
作为更安全的选择?
在发布规范上,添加:flutter_secure_storage: ^3.2.1+1
作为依赖项。
然后您可以使用异步的FlutterSecureStorage().write(key: key, value: value)
。
要阅读,只需使用encodedJson = FlutterSecureStorage().read(key: key)
,它也是异步的。
此外,您还必须使用yourModel.fromJson(json.decode(encodedJson))
,因此请确保还添加import 'dart:convert';