【发布时间】:2019-12-17 15:41:25
【问题描述】:
我试图了解如何在 Flutter 中存储地图列表、显示它,然后通过索引对其进行加减运算。我开始使用 jsonEncode/Decode 将整个内容保存为字符串,但我认为这不是正确的方法,而且我无法添加回它,因为它是字符串,而不是编码后的 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);
}
}
【问题讨论】: