I am trying to convert data decoded from json to Map<DateTime,List Here is the Code:
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>>;
But following error occurs:
[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
I have checked encoding.map() returns correct datatype(Map,List) but still this error appears.
CodePudding user response:
You can use Dart special Method of Map.from() Just Like:
_accounts = Map<DateTime,List<Account>>.from(encodedAccounts);
Here is the complete code:
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);
CodePudding user response:
It sometimes helps to add types to map
as here:
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);
Prints _InternalLinkedHashMap<DateTime, List<Account>> as expected. (Note that I changed the constructor of Account
for simplicity in this example.)