FLUTTER:如何显示 Open Weather Map 中的天气图标?

FLUTTER: How can I show the weather Icon from Open Weather Map?

我想在我的应用程序上显示开放的天气图标,但我不确定如何才能做到这一点。下面是我从 openweather 地图获取的数据示例,我还提供了一个如何获取其他数据的示例。

我的代码:

import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'GetLocation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() {
  runApp(AuraWeather());
}

class AuraWeather extends StatefulWidget {
  @override
  _AuraWeatherState createState() => _AuraWeatherState();
}

class _AuraWeatherState extends State<AuraWeather> {

  var apiKey = '5f10958d807d5c7e333ec2e54c4a5b16';
  var weatherIcon;
  var description;
  var maxTemp;
  var minTemp;
  var format_sunRise;
  var sunRise;
  var format_sunSet;
  var format_sunRiseEnd;
  var format_sunSetEnd;
  var sunSet;
  var temp;
  var city;

  @override
  Widget build(BuildContext context) {
    setState(() {
      getLocation();
    });

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(displayBackground()),
          ),
        ),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaY: 2, sigmaX: 2),
          child: Container(
            color: Colors.black.withOpacity(0.5),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              body: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      Container(
                        child: Center(
                          child: Text(
                            '$city',
                            style: TextStyle(
                              fontSize: 25,
                              color: Colors.white,
                              fontFamily: 'Roboto',
                            ),
                          ),
                        ),
                      ),
                      Container(
                        child: Icon(
                          FontAwesomeIcons.locationArrow,
                          color: Colors.white,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 80),
                        child: Text(
                          '$temp' + '°',
                          style: TextStyle(
                              fontSize: 50,
                              color: Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30),
                    child: Icon(
                      Icons.wb_sunny,
                      color: Colors.white,
                      size: 120,
                    ),
                  ),
                  Container(
                    child: Center(
                      child: Text(
                        '$maxTemp ° | $minTemp °',
                        style: TextStyle(fontSize: 20, color: Colors.white),
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      '$description',
                      style: TextStyle(fontSize: 20,
                          color: Colors.white,
                        fontFamily: 'Roboto mono',),
                    ),
                  ),
                  Container(
                    child: FlatButton(
                      child: Icon(
                        Icons.refresh,
                        color: Colors.white,
                        size: 40,
                      ),
                      color: Colors.transparent,
                      onPressed: () {
                        setState(
                              () {
                            getLocation();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // display background images based on current time
  displayBackground() {
    var now = DateTime.now();
    //var currentTime = DateFormat.jm().format(now);

    print('Sunrise time $format_sunRise');
    print('Sunset time $format_sunSet');
    print('Current time $now');

    if ((now.isAfter(format_sunRise)) && (now.isBefore(format_sunRiseEnd))){
      print('Morning');
     return'images/Moon.png';
    }else if((now.isAfter(format_sunRiseEnd)) && (now.isBefore(format_sunSet))){
      return 'images/Sun.png';
    }else if ((now.isAfter(format_sunSet)) && (now.isBefore(format_sunSetEnd))){
      print('Evening');
      return 'images/Moon.png';
    }else if((now.isAfter(format_sunSetEnd)) && (now.isBefore(format_sunRise))){
      return 'images/Blood.png';
    }
  }

  //getLocation
  void getLocation() async {
    Getlocation getlocation = Getlocation();
    await getlocation.getCurrentLocation();

    print(getlocation.latitude);
    print(getlocation.longitude);
    print(getlocation.city);
    city = getlocation.city;
    getTemp(getlocation.latitude, getlocation.longitude);
  }

  //Get current temp
  Future<void> getTemp(double lat, double lon) async {
    var now = DateTime.now();
    DateFormat dateFormat = new DateFormat.Hm();

    http.Response response = await http.get(
        'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
    //print(response.body);

    var dataDecoded = jsonDecode(response.body);

    description = dataDecoded['weather'][0]['description'];

    temp = dataDecoded['main']['temp'];
    temp = temp.toInt();

    maxTemp = dataDecoded['main']['temp_max'];
    maxTemp = maxTemp.toInt();

    minTemp = dataDecoded['main']['temp_min'];
    minTemp = minTemp.toInt();

    sunRise = dataDecoded['sys']['sunrise'];
    format_sunRise = DateTime.fromMillisecondsSinceEpoch(sunRise*1000);
    format_sunRiseEnd = format_sunRise.add(Duration(hours: 1));

    sunSet = dataDecoded['sys']['sunset'];
    format_sunSet = DateTime.fromMillisecondsSinceEpoch(sunSet*1000);
    format_sunSetEnd = format_sunSet.add(Duration(hours: 1));

    print('Current temp $temp');
    print('Max temp $maxTemp');
    print('Min temp $minTemp');

  }
}

示例数据:

{
    coord: {
        lon: 139.01,
        lat: 35.02
    },
    weather: [
     {
        id: 800,
        main: "Clear",
        description: "clear sky",
        icon: "01n"
     }
    ],
    base: "stations",
    main: {
        temp: 285.514,
        pressure: 1013.75,
        humidity: 100,
        temp_min: 285.514,
        temp_max: 285.514,
        sea_level: 1023.22,
        grnd_level: 1013.75
    },
    wind: {
        speed: 5.52,
        deg: 311
    },
    clouds: {
        all: 0
    },
    dt: 1485792967,
    sys: {
        message: 0.0025,
        country: "JP",
        sunrise: 1485726240,
        sunset: 1485763863
    },
    id: 1907296,
    name: "Tawarano",
    cod: 200
}

从上面的数据中,我可以得到:temptemp_maxtemp_min 和描述。我就是这样做的。

代码:

http.Response response = await http.get(
        'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
    //print(response.body);

    var dataDecoded = jsonDecode(response.body);

    description = dataDecoded['weather'][0]['description'];

    temp = dataDecoded['main']['temp'];
    temp = temp.toInt();

    maxTemp = dataDecoded['main']['temp_max'];
    maxTemp = maxTemp.toInt();

    minTemp = dataDecoded['main']['temp_min'];
    minTemp = minTemp.toInt();

如何显示来自 url 的图标? 图标将显示在 Scaffold 中的容器编号 5 内小部件。

对于这个 api 图标代码实际上有一个 url,在你的情况下就是这样。

icon_url = "http://openweathermap.org/img/w/" + dataDecoded["weather"]["icon"] +".png"

您可以将其用作图像:

Image.network(icon_url),

或直接:

Image.network('http://openweathermap.org/img/w/${dataDecoded["weather"]["icon"]}.png',),