如何在flutter中从openweathermap获取天气描述数据和图标沿着温度数据?

4sup72z8  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(173)

我设法从openweathermap中获取了临时数据。我设法从互联网上的这个JSON中获取了“主”数据。但是看看天气字段,描述在那里,但无法提取它。那里写着“clear”,图标为“01d”。我还将图标放入flutter中,其中有一个图像的URL,例如somelink/01d.png,我将获取并动态加载它:

{"coord":{"lon":28.9833,"lat":41.0351},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":15.87,"feels_like":15.16,"temp_min":15.04,"temp_max":17.09,"pressure":1024,"humidity":63},"visibility":10000,"wind":{"speed":3.09,"deg":120},"clouds":{"all":0},"dt":1668078936,"sys":{"type":1,"id":6970,"country":"TR","sunrise":1668055522,"sunset":1668091839},"timezone":10800,"id":745042,"name":"Istanbul","cod":200}

问题是,我有几种方法可以做到这一点。Futurebuilder在futurebuilder中,我不知道这是如何工作的。或者,从fetch函数返回一个数据数组。我不知道如何做到这一点。我完全困惑了。下面是我的简化代码:

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

class TempModel {
  final double temp;
  final double feels_like;
  final double temp_min;
  final double temp_max;
  final int pressure;
  final int humidity;

  TempModel({
    required this.temp,
    required this.feels_like,
    required this.temp_min,
    required this.temp_max,
    required this.pressure,
    required this.humidity,
  });

  factory TempModel.fromJson(Map<String, dynamic> json) {
    return TempModel(
      temp: json['temp'],
      feels_like: json['feels_like'],
      temp_min: json['temp_min'],
      temp_max: json['temp_max'],
      pressure: json['pressure'],
      humidity: json['humidity'],
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};
    data['temp'] = temp;
    data['feels_like'] = feels_like;
    data['temp_min'] = temp_min;
    data['temp_max'] = temp_max;
    data['pressure'] = pressure;
    data['humidity'] = humidity;
    return data;
  }
}

class WeatherModel {
  final TempModel main;

  WeatherModel({
    required this.main,
  });

  factory WeatherModel.fromJson(Map<String, dynamic> json) {
    return WeatherModel(
      main: TempModel.fromJson(json['main']),
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};
    data['main'] = main;
    return data;
  }
}

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

class TestPage extends StatelessWidget {
  const TestPage({Key? key}) : super(key: key);
  final String sehir1 = 'İstanbul';
  final String sehir2 = 'Ankara';
  final String sehir3 = 'İzmir';

  Future<WeatherModel?> fetchWeather(String sehir) async {
    //default olarak.

    final http.Response response = await http.get(Uri.parse(
        'https://api.openweathermap.org/data/2.5/weather?q=$sehir&units=metric&appid=666319c58bc57caab32599c61b82c50e'));
    print(response.body);
    print("");
    try {
      if (response.statusCode == 200) {
        WeatherModel weatherModel =
            WeatherModel.fromJson(jsonDecode(response.body));
        return weatherModel;
      } else {
        return null;
      }
    } catch (e) {
      log(e.toString(), name: "error");
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.orange,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: GridView.count(
          crossAxisCount: 2,
          children: <Widget>[
            Expanded(
              child: FutureBuilder(
                future: fetchWeather(sehir1),
                builder: (ctx, AsyncSnapshot<WeatherModel?> snapshot) {
                  if (!snapshot.hasData || snapshot.hasError) {
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  } else {
                    return Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.network(
                              'http://openweathermap.org/img/wn/01d.png'),
                          Text('$sehir1 Hava Durumu'),
                          Text(
                              'Hava sıcaklığı ${snapshot.data!.main.temp.toString()}'),
                          Text(
                              'Hissedilen sıcaklık ${snapshot.data!.main.feels_like.toString()}'),
                        ],
                      ),
                    );
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
06odsfpq

06odsfpq1#

weather是一个列表:

{
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ]
}

您必须使用其索引来获取值:

${snapshot.data!.weather[0].icon}

编辑:我发现您的模型没有考虑整个json。下面是完整的模型:

// To parse this JSON data, do
//
//     final weather = weatherFromJson(jsonString);

import 'dart:convert';

class Weather {
    Weather({
        required this.coord,
        required this.weather,
        required this.base,
        required this.main,
        required this.visibility,
        required this.wind,
        required this.clouds,
        required this.dt,
        required this.sys,
        required this.timezone,
        required this.id,
        required this.name,
        required this.cod,
    });

    final Coord coord;
    final List<WeatherElement> weather;
    final String base;
    final Main main;
    final int visibility;
    final Wind wind;
    final Clouds clouds;
    final int dt;
    final Sys sys;
    final int timezone;
    final int id;
    final String name;
    final int cod;

    factory Weather.fromRawJson(String str) => Weather.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Weather.fromJson(Map<String, dynamic> json) => Weather(
        coord: Coord.fromJson(json["coord"]),
        weather: List<WeatherElement>.from(json["weather"].map((x) => WeatherElement.fromJson(x))),
        base: json["base"],
        main: Main.fromJson(json["main"]),
        visibility: json["visibility"],
        wind: Wind.fromJson(json["wind"]),
        clouds: Clouds.fromJson(json["clouds"]),
        dt: json["dt"],
        sys: Sys.fromJson(json["sys"]),
        timezone: json["timezone"],
        id: json["id"],
        name: json["name"],
        cod: json["cod"],
    );

    Map<String, dynamic> toJson() => {
        "coord": coord.toJson(),
        "weather": List<dynamic>.from(weather.map((x) => x.toJson())),
        "base": base,
        "main": main.toJson(),
        "visibility": visibility,
        "wind": wind.toJson(),
        "clouds": clouds.toJson(),
        "dt": dt,
        "sys": sys.toJson(),
        "timezone": timezone,
        "id": id,
        "name": name,
        "cod": cod,
    };
}

class Clouds {
    Clouds({
        required this.all,
    });

    final int all;

    factory Clouds.fromRawJson(String str) => Clouds.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Clouds.fromJson(Map<String, dynamic> json) => Clouds(
        all: json["all"],
    );

    Map<String, dynamic> toJson() => {
        "all": all,
    };
}

class Coord {
    Coord({
        required this.lon,
        required this.lat,
    });

    final double lon;
    final double lat;

    factory Coord.fromRawJson(String str) => Coord.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Coord.fromJson(Map<String, dynamic> json) => Coord(
        lon: json["lon"].toDouble(),
        lat: json["lat"].toDouble(),
    );

    Map<String, dynamic> toJson() => {
        "lon": lon,
        "lat": lat,
    };
}

class Main {
    Main({
        required this.temp,
        required this.feelsLike,
        required this.tempMin,
        required this.tempMax,
        required this.pressure,
        required this.humidity,
    });

    final double temp;
    final double feelsLike;
    final double tempMin;
    final double tempMax;
    final int pressure;
    final int humidity;

    factory Main.fromRawJson(String str) => Main.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Main.fromJson(Map<String, dynamic> json) => Main(
        temp: json["temp"].toDouble(),
        feelsLike: json["feels_like"].toDouble(),
        tempMin: json["temp_min"].toDouble(),
        tempMax: json["temp_max"].toDouble(),
        pressure: json["pressure"],
        humidity: json["humidity"],
    );

    Map<String, dynamic> toJson() => {
        "temp": temp,
        "feels_like": feelsLike,
        "temp_min": tempMin,
        "temp_max": tempMax,
        "pressure": pressure,
        "humidity": humidity,
    };
}

class Sys {
    Sys({
        required this.type,
        required this.id,
        required this.country,
        required this.sunrise,
        required this.sunset,
    });

    final int type;
    final int id;
    final String country;
    final int sunrise;
    final int sunset;

    factory Sys.fromRawJson(String str) => Sys.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Sys.fromJson(Map<String, dynamic> json) => Sys(
        type: json["type"],
        id: json["id"],
        country: json["country"],
        sunrise: json["sunrise"],
        sunset: json["sunset"],
    );

    Map<String, dynamic> toJson() => {
        "type": type,
        "id": id,
        "country": country,
        "sunrise": sunrise,
        "sunset": sunset,
    };
}

class WeatherElement {
    WeatherElement({
        required this.id,
        required this.main,
        required this.description,
        required this.icon,
    });

    final int id;
    final String main;
    final String description;
    final String icon;

    factory WeatherElement.fromRawJson(String str) => WeatherElement.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory WeatherElement.fromJson(Map<String, dynamic> json) => WeatherElement(
        id: json["id"],
        main: json["main"],
        description: json["description"],
        icon: json["icon"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "main": main,
        "description": description,
        "icon": icon,
    };
}

class Wind {
    Wind({
        required this.speed,
        required this.deg,
    });

    final double speed;
    final int deg;

    factory Wind.fromRawJson(String str) => Wind.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Wind.fromJson(Map<String, dynamic> json) => Wind(
        speed: json["speed"].toDouble(),
        deg: json["deg"],
    );

    Map<String, dynamic> toJson() => {
        "speed": speed,
        "deg": deg,
    };
}

相关问题