Home > Enterprise >  I'm trying to make a simple app in flutter that fetches data from an API. However when I try ru
I'm trying to make a simple app in flutter that fetches data from an API. However when I try ru

Time:09-04

"Dart Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' "

It says that the error is in the following line:

for(var jsonObject in jsonObjects){
    objects.add(Object.fromJson(jsonObject));
    }

For context, the entire code is this:

class _HomePageState extends State<HomePage> {
  final List<Object> _objects = [];
  Future<List<Object>> fetchData() async{
    const String urlString = 'https://api.publicapis.org/entries';
    final Uri url = Uri.parse(urlString);
    var response = await http.get(url);
    final List<Object> objects = [];
    if(response.statusCode == 200){
      var jsonObjects = json.decode(response.body);
      print("Step 1");
      for(var jsonObject in jsonObjects){
        objects.add(Object.fromJson(jsonObject));
        
      }
    }
    return objects;
  }

Any help would be greatly appreciated. Thanks.

CodePudding user response:

Main problem is that response.body is not a list of elements, and you are assuming it is. Instead of that, it's a "key" : "value" type of json object, which cannot be iterated.

The for (var e in collection) syntax is made to be used with an Iterable collection, and _InternalLinkedHashMap (and maps in general) are not iterables.

The solution is to parse the response properly. Check this link if you want to follow best practices for flutter development json parsing.

CodePudding user response:

Your api response's body is a Map:

{"count":1425,
 "entries":[
    {"API":"AdoptAPet","Description":"Resource to help get pets adopted","Auth":"apiKey","HTTPS":true,"Cors":"yes","Link":"https://www.adoptapet.com/public/apis/pet_list.html","Category":"Animals"},
    {"API":"Axolotl","Description":"Collection of axolotl pictures and facts","Auth":"","HTTPS":true,"Cors":"no","Link":"https://theaxolotlapi.netlify.app/","Category":"Animals"},
     ...
 ]
}

what you are looking for is a list, Try this:

var jsonObjects = json.decode(response.body["entries"]);
      print("Step 1");
      for(var jsonObject in jsonObjects){
        objects.add(Object.fromJson(jsonObject));
        
      }
  • Related