FLUTTER: 我怎样才能显示开放天气地图的天气图标?

问题描述 投票:0回答:1

我想在我的应用程序上显示开放的天气图标,但我不知道如何能做到这一点。我的数据样本是来自于 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');

  }
}

SAMPLE DATA:

{
    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
}

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

CODE:

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中显示ICON? Icon将显示在Scaffold widgget的5号容器内。

flutter dart weather openweathermap weather-api
1个回答
2
投票

对于这个api图标代码有一个网址,实际上,它会像在你的情况下。

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',),
© www.soinside.com 2019 - 2024. All rights reserved.