如何在抖动中将Json解码为DateTime格式?

问题描述 投票:0回答:1

im试图使用共享首选项将我的List数据存储在磁盘存储中,但是当我重新构建/重新启动应用程序时,尝试从内存中再次获取数据时,idk如何将json转换回DateTime格式。

这是我的代码:

  String id;
  String title;
  double amount;
  DateTime date;

  Transaction({
    @required this.id,
    @required this.title,
    @required this.amount,
    @required this.date,
  });

  Transaction.fromMap(Map map)
      : this.id = map['id'],
        this.title = map['title'],
        this.date = map['date'],
        this.amount = map['amount'];

  Map toMap() {
    return {
      'id': this.id,
      'title': this.title,
      'date': this.date.toIso8601String(),
      'amount': this.amount,
    };
  }
}

这里我在这里使用sharedPreferences

@override
  void initState() {
    initSharedPreferences();
    super.initState();
  }

  initSharedPreferences() async {
    sharedPreferences = await SharedPreferences.getInstance();
    loadData();
  }


  void saveData() {
    setState(() {
      List<String> spList =
          transactions.map((item) => json.encode(item.toMap())).toList();
      var list = sharedPreferences.setStringList('list', spList);
      print(list);
    });
  }

  void loadData() {
    List<String> spList = sharedPreferences.getStringList('list');
    transactions =
        spList.map((item) => Transaction.fromMap(json.decode(item))).toList();
    setState(() {});
    print(transactions);
  }
json flutter dart sharedpreferences datetime-format
1个回答
0
投票
在Transaction.fromMap构造函数中
© www.soinside.com 2019 - 2024. All rights reserved.