Reputation: 2510
This is my json structure.
[
[
{
"nos": 0,
"name": "A S MUSIC AND DANCE A CULTURAL ORGANIZATION",
"unique_id": "AN/2020/0259067",
"reg_details": [
{
"registered_with": "Registrar of Societies"
},
{
"type_of_ngo": "Registered Societies (Non-Government)"
This is working fine.
String jsonString = await _loadANgoAsset();
final jsonResponse = json.decode(jsonString);
String name = jsonResponse[0][0]['name'];
debugPrint("Name of NGO is $name");
But when I want to loop throug a key of various entities of data using this code:
List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];
allNamesOfNGO.forEach((allNamesOfNGO) {
(allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
print(key);
(value as Map<String, dynamic>).forEach((key2, value2) {
print(key2);
print(value2);
});
});
});
The following error occurs:
E/flutter ( 4683): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'
Help please!
Upvotes: 0
Views: 78
Reputation: 127
List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];
This line tries to assign name of first ngo(String) to allNamesOfNGO(List), which results in the above error. To overcome this error, replace the above code with this:
List<dynamic> allNamesOfNGO = jsonResponse[0];
allNamesOfNGO.forEach((allNamesOfNGO) {
(allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
print(key);
print(value);
if(key == "reg_details") {
value.forEach(regDetail) {
print(regDetail);
});
}
});
});
You don't need innermost forEach loop as you have already got the key, value pair before that loop. In the innermost forEach loop, you are trying to loop through individual key like nos, name and unique_is(which is either a string or an int) which isn't possible.
Value of reg_details is a list. So you can loop through it, but for that you have to check if key == "reg_details"
.
Upvotes: 1
Reputation: 1
because you declare it as String and then loop it as dynamic .try
List<string>
instead of
List<dynamic>.
Upvotes: 0