如何在 flutter 中将 Json 解码为 DateTime 格式?
how to decode Json to DateTime format in flutter?
我正在尝试使用共享首选项将我的列表数据存储在磁盘存储中,但是当我 rebuild/restart 尝试再次从内存中获取数据时,我不知道如何将 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);
}
在Transaction.fromMap构造函数中
替换
this.date = map['date'],
和
this.date = DateTime.parse(map['date']),
我正在尝试使用共享首选项将我的列表数据存储在磁盘存储中,但是当我 rebuild/restart 尝试再次从内存中获取数据时,我不知道如何将 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);
}
在Transaction.fromMap构造函数中
替换
this.date = map['date'],
和
this.date = DateTime.parse(map['date']),