Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 使用共享首选项存储地图字符串列表_Flutter_Dart - Fatal编程技术网

Flutter 使用共享首选项存储地图字符串列表

Flutter 使用共享首选项存储地图字符串列表,flutter,dart,Flutter,Dart,我试图理解如何在flifter中存储贴图列表,显示它,然后通过索引进行添加和减去。我开始使用JSONECODE/Decode将整个内容保存为字符串,但我认为这不是正确的方法,而且我无法将其添加回去,因为编码后它是字符串,不再是列表。非常感谢您的帮助 class Favs extends StatefulWidget { @override _Favs createState() => _Favs(); } class _Favs extends State<Favs

我试图理解如何在flifter中存储贴图列表,显示它,然后通过索引进行添加和减去。我开始使用JSONECODE/Decode将整个内容保存为字符串,但我认为这不是正确的方法,而且我无法将其添加回去,因为编码后它是字符串,不再是列表。非常感谢您的帮助

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);

}

}

解码和编码是写的方式。您为什么不尝试将Flatter\u secure\u存储作为更安全的选择

在pubspec上,添加:flatter\u secure\u存储:^3.2.1+1作为依赖项

然后可以使用异步的securestorage.writekey:key,value:value

要读取,只需使用encodedJson=securestorage.readkey:key,它也是异步的

此外,您还必须使用您的model.fromJsonjson.decodeCodedJSON,因此请确保您还添加了import'dart:convert'