我正在嘗試將從 json 解碼的資料轉換為 Map<DateTime,List 這是代碼:
var encodingaccounts = json.decode(gettingAccounts!);
var encodedAccounts = encodingTasks.map((dateTime, Accounts) {
List<Account> convertedAccountsType = [];
for (var Account in Accounts) {
String _summary = Account['summary'];
String _description = Account['description'];
String _category = Account['category'];
bool _isDone = Account['isDone'];
convertedaccountsType.add(Account(_summary,
category: _category, description: _description, isDone: _isDone));
}
return MapEntry(DateTime.parse(dateTime), convertedaccountsype);
});
_accounts = encodedAccounts as Map<DateTime, List<Account>>;
但是出現以下錯誤:
[ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: type
'_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<DateTime,
List<Account>>' in type cast
我檢查了encoding.map()回傳正確的資料型別(Map,List) 但仍然出現這個錯誤。
uj5u.com熱心網友回復:
您可以使用 Map.from() 的 Dart 特殊方法,就像:
_accounts = Map<DateTime,List<Account>>.from(encodedAccounts);
這是完整的代碼:
var encodingaccounts = json.decode(gettingAccounts!);
var encodedAccounts = encodingTasks.map((dateTime, Accounts) {
List<Account> convertedAccountsType = [];
for (var Account in Accounts) {
String _summary = Account['summary'];
String _description = Account['description'];
String _category = Account['category'];
bool _isDone = Account['isDone'];
convertedaccountsType.add(Account(_summary,
category: _category, description: _description, isDone: _isDone));
}
return MapEntry(DateTime.parse(dateTime), convertedaccountsype);
});
w_accounts = Map<DateTime,List<Account>>.from(encodedAccount);
uj5u.com熱心網友回復:
有時將型別添加到map這里會有所幫助:
final _accounts =
et.map<DateTime, List<Account>>((dateTime, accounts) => MapEntry(
DateTime.parse(dateTime),
accounts
.map<Account>((e) => Account(
e['summary'],
e['category'],
e['description'],
e['isDone'],
))
.toList()));
print(_accounts.runtimeType);
按預期列印_InternalLinkedHashMap<DateTime, List<Account>>。(請注意,Account在此示例中,為了簡單起見,我更改了 的建構式。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377187.html
