【问题标题】:Store a List of Map Strings using Shared Preferences使用共享首选项存储地图字符串列表
【发布时间】: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);

}

}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    解码和编码是写的方式。为什么不试试flutter_secure_storage 作为更安全的选择?

    在您的 pubspec 中,添加: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';

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-16
      • 2021-11-08
      • 1970-01-01
      • 2021-06-24
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多