【问题标题】:how to decode Json to DateTime format in flutter?如何在颤动中将 Json 解码为 DateTime 格式?
【发布时间】:2020-07-23 17:24:33
【问题描述】:

我正在尝试使用共享首选项将我的列表数据存储在磁盘存储中,但是在我重建/重新启动应用程序时尝试再次从内存中获取数据时如何将 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】:

    在 Transaction.fromMap 构造函数中

    替换

    this.date = map['date'],
    

    this.date = DateTime.parse(map['date']),
    

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      相关资源
      最近更新 更多