Home > Software design >  How can I iterate over each item in json Flutter?
How can I iterate over each item in json Flutter?

Time:01-02

enter image description hereI'm trying to build a weather forecast app and trying to iterate over temperature. I can't seem to figure out how I can only get data for temperature.


{
  "cod": "200",
  "message": 0,
  "cnt": 40,
  "list": [
    {
      "dt": 1641049200,
      "main": {
        "temp": 14.33,
        "feels_like": 13.88,
        "temp_min": 13.46,
        "temp_max": 14.33,
        "pressure": 1017,
        "sea_level": 1017,
        "grnd_level": 1013,
        "humidity": 79,
        "temp_kf": 0.87
      },
      "weather": [
        {
          "id": 804,
          "main": "Clouds",
          "description": "overcast clouds",
          "icon": "04d"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 5.51,
        "deg": 212,
        "gust": 13.66
      },
      "visibility": 10000,
      "pop": 0.2,
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-01 15:00:00"
    },
    {
      "dt": 1641060000,
      "main": {
        "temp": 13.68,
        "feels_like": 13.27,
        "temp_min": 12.37,
        "temp_max": 13.68,
        "pressure": 1017,
        "sea_level": 1017,
        "grnd_level": 1013,
        "humidity": 83,
        "temp_kf": 1.31
      },
      "weather": [
        {
          "id": 804,
          "main": "Clouds",
          "description": "overcast clouds",
          "icon": "04n"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 5.06,
        "deg": 223,
        "gust": 13.39
      },
      "visibility": 10000,
      "pop": 0.06,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-01 18:00:00"
    },
    {
      "dt": 1641276000,
      "main": {
        "temp": 5.55,
        "feels_like": 0.95,
        "temp_min": 5.55,
        "temp_max": 5.55,
        "pressure": 995,
        "sea_level": 995,
        "grnd_level": 992,
        "humidity": 91,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 501,
          "main": "Rain",
          "description": "moderate rain",
          "icon": "10n"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 7.8,
        "deg": 63,
        "gust": 14.78
      },
      "visibility": 10000,
      "pop": 1,
      "rain": {
        "3h": 8.62
      },
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-04 06:00:00"
    },
    {
      "dt": 1641286800,
      "main": {
        "temp": 4.47,
        "feels_like": -0.98,
        "temp_min": 4.47,
        "temp_max": 4.47,
        "pressure": 991,
        "sea_level": 991,
        "grnd_level": 988,
        "humidity": 93,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 501,
          "main": "Rain",
          "description": "moderate rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 9.53,
        "deg": 57,
        "gust": 18.19
      },
      "visibility": 4030,
      "pop": 1,
      "rain": {
        "3h": 4.5
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-04 09:00:00"
    },
    {
      "dt": 1641297600,
      "main": {
        "temp": 2.47,
        "feels_like": -4.07,
        "temp_min": 2.47,
        "temp_max": 2.47,
        "pressure": 989,
        "sea_level": 989,
        "grnd_level": 986,
        "humidity": 95,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 501,
          "main": "Rain",
          "description": "moderate rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 11.11,
        "deg": 47,
        "gust": 21.37
      },
      "visibility": 77,
      "pop": 1,
      "rain": {
        "3h": 4.42
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-04 12:00:00"
    },
    {
      "dt": 1641308400,
      "main": {
        "temp": 1.66,
        "feels_like": -4.74,
        "temp_min": 1.66,
        "temp_max": 1.66,
        "pressure": 997,
        "sea_level": 997,
        "grnd_level": 994,
        "humidity": 92,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 601,
          "main": "Snow",
          "description": "snow",
          "icon": "13d"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 9.71,
        "deg": 6,
        "gust": 19.57
      },
      "visibility": 4352,
      "pop": 1,
      "snow": {
        "3h": 5.76
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-04 15:00:00"
    },
    {
      "dt": 1641319200,
      "main": {
        "temp": 1.91,
        "feels_like": -3.13,
        "temp_min": 1.91,
        "temp_max": 1.91,
        "pressure": 1006,
        "sea_level": 1006,
        "grnd_level": 1003,
        "humidity": 97,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 601,
          "main": "Snow",
          "description": "snow",
          "icon": "13n"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 6.22,
        "deg": 325,
        "gust": 13.83
      },
      "visibility": 54,
      "pop": 1,
      "snow": {
        "3h": 1.79
      },
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-04 18:00:00"
    },
    {
      "dt": 1641330000,
      "main": {
        "temp": 1.61,
        "feels_like": -2.74,
        "temp_min": 1.61,
        "temp_max": 1.61,
        "pressure": 1011,
        "sea_level": 1011,
        "grnd_level": 1008,
        "humidity": 80,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 804,
          "main": "Clouds",
          "description": "overcast clouds",
          "icon": "04n"
        }
      ],
      "clouds": {
        "all": 99
      },
      "wind": {
        "speed": 4.71,
        "deg": 310,
        "gust": 11.56
      },
      "visibility": 10000,
      "pop": 0.24,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-04 21:00:00"
    },
    {
      "dt": 1641340800,
      "main": {
        "temp": 0.66,
        "feels_like": -3.04,
        "temp_min": 0.66,
        "temp_max": 0.66,
        "pressure": 1014,
        "sea_level": 1014,
        "grnd_level": 1010,
        "humidity": 79,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 803,
          "main": "Clouds",
          "description": "broken clouds",
          "icon": "04n"
        }
      ],
      "clouds": {
        "all": 80
      },
      "wind": {
        "speed": 3.4,
        "deg": 283,
        "gust": 10.4
      },
      "visibility": 10000,
      "pop": 0.02,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-05 00:00:00"
    },
    {
      "dt": 1641351600,
      "main": {
        "temp": 0.47,
        "feels_like": -3.77,
        "temp_min": 0.47,
        "temp_max": 0.47,
        "pressure": 1015,
        "sea_level": 1015,
        "grnd_level": 1012,
        "humidity": 76,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01n"
        }
      ],
      "clouds": {
        "all": 4
      },
      "wind": {
        "speed": 4.09,
        "deg": 278,
        "gust": 12.45
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-05 03:00:00"
    },
    {
      "dt": 1641362400,
      "main": {
        "temp": 0.48,
        "feels_like": -3.77,
        "temp_min": 0.48,
        "temp_max": 0.48,
        "pressure": 1016,
        "sea_level": 1016,
        "grnd_level": 1013,
        "humidity": 83,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 802,
          "main": "Clouds",
          "description": "scattered clouds",
          "icon": "03n"
        }
      ],
      "clouds": {
        "all": 27
      },
      "wind": {
        "speed": 4.11,
        "deg": 279,
        "gust": 12.15
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-05 06:00:00"
    },
    {
      "dt": 1641373200,
      "main": {
        "temp": 0.79,
        "feels_like": -3.36,
        "temp_min": 0.79,
        "temp_max": 0.79,
        "pressure": 1018,
        "sea_level": 1018,
        "grnd_level": 1015,
        "humidity": 83,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01d"
        }
      ],
      "clouds": {
        "all": 6
      },
      "wind": {
        "speed": 4.07,
        "deg": 288,
        "gust": 12.29
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-05 09:00:00"
    },
    {
      "dt": 1641384000,
      "main": {
        "temp": 2.72,
        "feels_like": -0.97,
        "temp_min": 2.72,
        "temp_max": 2.72,
        "pressure": 1020,
        "sea_level": 1020,
        "grnd_level": 1017,
        "humidity": 76,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01d"
        }
      ],
      "clouds": {
        "all": 6
      },
      "wind": {
        "speed": 4.04,
        "deg": 300,
        "gust": 10.81
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-05 12:00:00"
    },
    {
      "dt": 1641394800,
      "main": {
        "temp": 2.66,
        "feels_like": -0.65,
        "temp_min": 2.66,
        "temp_max": 2.66,
        "pressure": 1021,
        "sea_level": 1021,
        "grnd_level": 1018,
        "humidity": 76,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01d"
        }
      ],
      "clouds": {
        "all": 4
      },
      "wind": {
        "speed": 3.45,
        "deg": 304,
        "gust": 9.24
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-05 15:00:00"
    },
    {
      "dt": 1641405600,
      "main": {
        "temp": 1.16,
        "feels_like": -1.26,
        "temp_min": 1.16,
        "temp_max": 1.16,
        "pressure": 1022,
        "sea_level": 1022,
        "grnd_level": 1019,
        "humidity": 84,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01n"
        }
      ],
      "clouds": {
        "all": 4
      },
      "wind": {
        "speed": 2.13,
        "deg": 287,
        "gust": 6.43
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-05 18:00:00"
    },
    {
      "dt": 1641416400,
      "main": {
        "temp": 0.63,
        "feels_like": -0.93,
        "temp_min": 0.63,
        "temp_max": 0.63,
        "pressure": 1023,
        "sea_level": 1023,
        "grnd_level": 1020,
        "humidity": 86,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01n"
        }
      ],
      "clouds": {
        "all": 0
      },
      "wind": {
        "speed": 1.43,
        "deg": 257,
        "gust": 3.25
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-05 21:00:00"
    },
    {
      "dt": 1641427200,
      "main": {
        "temp": 0.4,
        "feels_like": -1.81,
        "temp_min": 0.4,
        "temp_max": 0.4,
        "pressure": 1023,
        "sea_level": 1023,
        "grnd_level": 1020,
        "humidity": 87,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01n"
        }
      ],
      "clouds": {
        "all": 0
      },
      "wind": {
        "speed": 1.86,
        "deg": 229,
        "gust": 4.32
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-06 00:00:00"
    },
    {
      "dt": 1641438000,
      "main": {
        "temp": 0.69,
        "feels_like": -1.53,
        "temp_min": 0.69,
        "temp_max": 0.69,
        "pressure": 1022,
        "sea_level": 1022,
        "grnd_level": 1019,
        "humidity": 84,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 803,
          "main": "Clouds",
          "description": "broken clouds",
          "icon": "04n"
        }
      ],
      "clouds": {
        "all": 57
      },
      "wind": {
        "speed": 1.9,
        "deg": 193,
        "gust": 6.1
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-06 03:00:00"
    },
    {
      "dt": 1641448800,
      "main": {
        "temp": 1.68,
        "feels_like": -0.71,
        "temp_min": 1.68,
        "temp_max": 1.68,
        "pressure": 1021,
        "sea_level": 1021,
        "grnd_level": 1017,
        "humidity": 82,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 803,
          "main": "Clouds",
          "description": "broken clouds",
          "icon": "04n"
        }
      ],
      "clouds": {
        "all": 79
      },
      "wind": {
        "speed": 2.19,
        "deg": 170,
        "gust": 9.32
      },
      "visibility": 10000,
      "pop": 0,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2022-01-06 06:00:00"
    },
    {
      "dt": 1641459600,
      "main": {
        "temp": 4.29,
        "feels_like": 0.69,
        "temp_min": 4.29,
        "temp_max": 4.29,
        "pressure": 1019,
        "sea_level": 1019,
        "grnd_level": 1016,
        "humidity": 79,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 804,
          "main": "Clouds",
          "description": "overcast clouds",
          "icon": "04d"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 4.53,
        "deg": 213,
        "gust": 12.22
      },
      "visibility": 10000,
      "pop": 0.04,
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-06 09:00:00"
    },
    {
      "dt": 1641470400,
      "main": {
        "temp": 4.74,
        "feels_like": 0.46,
        "temp_min": 4.74,
        "temp_max": 4.74,
        "pressure": 1017,
        "sea_level": 1017,
        "grnd_level": 1014,
        "humidity": 92,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 100
      },
      "wind": {
        "speed": 6.25,
        "deg": 204,
        "gust": 13.59
      },
      "visibility": 10000,
      "pop": 0.71,
      "rain": {
        "3h": 1.28
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2022-01-06 12:00:00"
    }
  ],
  "city": {
    "id": 2643743,
    "name": "London",
    "coord": {
      "lat": 51.5085,
      "lon": -0.1257
    },
    "country": "GB",
    "population": 1000000,
    "timezone": 0,
    "sunrise": 1641024368,
    "sunset": 1641052893
  }
}

in weatherData.dart

class WeatherData {
  String? placeName;
  num? temperature;
  num? feels_like;
  num? pressure;
  num? humidity;
  num? wind_speed;

  WeatherData({
    this.placeName,
    this.temperature,
    this.feels_like,
    this.pressure,
    this.humidity,
    this.wind_speed,
  });

  WeatherData.fromJson(Map<String, dynamic> json) {
    placeName = json['city']['name'];
    temperature = json['list'][0]['main']['temp'];
    feels_like = json['list'][0]['main']['temp'];
    pressure = json['list'][0]['main']['temp'];
    humidity = json['list'][0]['main']['temp'];
    wind_speed = json['list'][0]['main']['temp'];
  }
}

in forecastData.dart

import 'package:forecast/models/weather_data.dart';

class ForecastData {
  final List list;

  ForecastData({required this.list});

  factory ForecastData.fromJson(Map<String, dynamic> json) {
    var list = json['list']?.map((e) => e)?.toList(growable: true) ?? [];

    list.forEach((e) {
      WeatherData w = WeatherData(
          placeName: json['city']['name'],
          temperature: e['main']['temp'],
          feels_like: e['main']['temp'],
          pressure: e['main']['temp'],
          humidity: e['main']['temp'],
          wind_speed: e['main']['temp']);

      list.add(w);
      print(w);
    });

    return ForecastData(
      list: list,
    );
  }
}

In weather_item.dart

import 'package:flutter/material.dart';
import 'package:forecast/models/weather_data.dart';

class WeatherItem extends StatelessWidget {
  final WeatherData weather;

  const WeatherItem({Key? key, required this.weather}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Text('${weather.placeName}',
                style: const TextStyle(color: Colors.white)),
            Text('${weather.temperature}',
                style: const TextStyle(color: Colors.white, fontSize: 32.0)),
            Text('${weather.feels_like.toString()}°F',
                style: const TextStyle(color: Colors.white)),
            Text('${weather.humidity}',
                style: const TextStyle(color: Colors.white)),
            Text('${weather.wind_speed}',
                style: const TextStyle(color: Colors.white)),
          ],
        ),
      ),
    );
  }
}

in main.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:forecast/models/forecast_data.dart';
import 'package:forecast/models/weather_data.dart';
import 'package:forecast/widgets/weather.dart';
import 'package:forecast/widgets/weather_item.dart';
import 'package:http/http.dart' as http;

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  WeatherData weatherData = WeatherData();
  ForecastData? forecastData;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();

    loadWeather();
    loadForecast();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Weather App',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: Scaffold(
        backgroundColor: Colors.blueGrey,
        appBar: AppBar(
          title: const Text('Flutter Weather App'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Weather(weather: weatherData)),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: IconButton(
                  icon: const Icon(Icons.refresh),
                  tooltip: 'Refresh',
                  onPressed: () {},
                  color: Colors.white,
                ),
              ),
              SafeArea(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    height: 200.0,
                    child: ListView.builder(
                        itemBuilder: (context, index) => WeatherItem(
                            weather: forecastData?.list.elementAt(index))),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  loadWeather() async {
    setState(() {
      isLoading = true;
    });

    String url =
        'https://api.openweathermap.org/data/2.5/forecast?q=London&units=metric&appid=API';

    http.Response response = await http.get(Uri.parse(url));

    if (response.statusCode == 200 && response.statusCode == 200) {
      return setState(() {
        weatherData = WeatherData.fromJson(jsonDecode(response.body));
      
       
        isLoading = false;
      });
    }
  }
  loadForecast() async {
    setState(() {
      isLoading = true;
    });

    String url =
        'https://api.openweathermap.org/data/2.5/forecast?q=London&units=metric&appid=API';

    http.Response response = await http.get(Uri.parse(url));

    if (response.statusCode == 200 && response.statusCode == 200) {
      return setState(() {
        forecastData = ForecastData.fromJson(jsonDecode(response.body));

        isLoading = false;
      });
    }
  }
}
}

When I debug it I get an error in weather_item.dart that says following

NoSuchMethodError (NoSuchMethodError: The getter 'placeName' was called on null. Receiver: null Tried calling: placeName)

and I also get an error that says type Null is not a subtype of type 'WeatherData' on the screen emulator when I run it..

I can only get weatherData rendered not forecastData.. any help is appreciated!

CodePudding user response:

try using futurebuilder when printing data i'm not sure if you might be trying to reach them before the data arrives

CodePudding user response:

On your model class, variables are nullable

class WeatherData {
  String? placeName;

Text widget doesn't take null value, therefore you need to handle it.

You can provide default value like

Text('${weather.placeName?? "default value"}',

Or don't render while it is null

if(weather.placeName!=null)Text('${weather.placeName!}'

Check, I'm using ! after making sure it will never get null.

Check this to understanding-null-safety

  • Related