Flutter error: _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>')

Viewed 42

I am trying to run an API through my application and have come across this dynamic error: _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>')

The error happens on line 23: for (var u in jsonData) {

I am not too sure on how to fix this, would appreciate any help!!

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MaterialApp(
      home: HomePage(),
      debugShowCheckedModeBanner: false,
    ));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future getUserData() async {
    var response = await http.get(Uri.parse(
        'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m'));
    var jsonData = jsonDecode(response.body);
    List users = [];
for (var u in jsonData) {
  User user = User(
      u['hourly'],
      u['time'],
      u['temperature_2m'],
      u['longitude'],
      u['generationtime_ms'],
      u['hourly_units'],
      u['latitude']);
  users.add(user);
}

return users;
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Rangers Tool'),
      ),
      body: Center(
          child: Card(
              child: FutureBuilder(
        future: getUserData(),
        builder: (context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          } else {
            return ListView.builder(
                itemCount: snapshot.data?.length,
                itemBuilder: (context, i) {
                  return ListTile(
                    title: Text(snapshot.data[i].longitude),
                    subtitle: Text(snapshot.data[i].latitude),
                  );
                });
          }
        },
      ))),
    );
  }
}

class User {
  final String? hourly,
      time,
      temperature_2m,
      longitude,
      generationtime_m,
      hourly_units,
      latitude;

  User(this.longitude, this.latitude, this.hourly, this.time,
      this.temperature_2m, this.generationtime_m, this.hourly_units);
}
1 Answers

jsonData is not an Iterable that you can make a for loop on, its a Map<String, dynamic>

you have to provide the API response so I can tell you the correct implementation. but for now, if this API returns a list of users then you should write it as follows

List users = (response.body as List?)?.map((e) => User(
  u['hourly'],
  u['time'],
  u['temperature_2m'],
  u['longitude'],
  u['generationtime_ms'],
  u['hourly_units'],
  u['latitude'])).toList() ?? [];

if you are not using null safety feel free to ignore the ?

Related