颤振条件背景图像添加

时间:2020-08-03 13:52:09

标签: flutter dart mobile

我正在使用Flutter开发天气应用程序。我正在考虑设计一个会根据天气而变化的背景。但是我不知道如何。我看到了类似的问题,但没有看到任何好处。

这是我所有的代码;

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:uygulama1/Weather.dart';
import 'package:uygulama1/WeatherItem.dart';
import 'package:uygulama1/WeatherData.dart';
import 'package:uygulama1/ForecastData.dart';

//PROJECT'S ROOT
void main() {
  runApp(MaterialApp(
    title: "WeatherApp",
    home: MyApp(),
  ));
}

//PROJECTS MAIN CLASS
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  bool isLoading = false;
  WeatherData weatherData;
  ForecastData forecastData;
  Location _location = new Location();
  String error;
  @override
  void initState() {
    super.initState();

    loadWeather();
  }

  Future<LocationData> getLocationData() async {
    return await _location.getLocation();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Weather App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
          backgroundColor: Colors.tealAccent,
          appBar: AppBar(
            title: Text('Flutter Weather App'),
          ),
          body: Center(
              child: Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
              
                //BACKGROUND IMAGE
            Container(
              decoration: BoxDecoration(
                image: new DecorationImage(
                  image: new AssetImage("assets/rain.jpg"),fit: BoxFit.cover
                  ),
                  ),
                  
            ),
                //END
                
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: weatherData != null
                        ? Weather(weather: weatherData)
                        : Container(),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: isLoading
                        ? CircularProgressIndicator(
                            strokeWidth: 2.0,
                            valueColor:
                                new AlwaysStoppedAnimation(Colors.black),
                          )
                        : IconButton(
                            icon: new Icon(Icons.refresh),
                            tooltip: 'Refresh',
                            onPressed: loadWeather,
                            color: Colors.black,
                          ),
                  ),

                ],
              ),
            ),
            SafeArea(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Container(
                  height: 200.0,
                  child: forecastData != null
                      ? ListView.builder(
                          itemCount: forecastData.list.length,
                          scrollDirection: Axis.horizontal,
                          itemBuilder: (context, index) => WeatherItem(
                              weather: forecastData.list.elementAt(index)))
                      : Container(),
                ),
              ),
            )
          ]))),
    );
  }

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

    LocationData location;
    try {
      location = await getLocationData();

      error = null;
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'Permission denied';
      } else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
        error =
            'Permission denied - please ask the user to enable it from the app settings';
      }

      location = null;
    }

    if (location != null) {
      final lat = location.latitude;
      final lon = location.longitude;

      final weatherResponse = await http.get(
          'https://api.openweathermap.org/data/2.5/weather?APPID=d89de3f0b2dedfe4f923f1e7f709953a&lat=${lat.toString()}&lon=${lon.toString()}');
      final forecastResponse = await http.get(
          'https://api.openweathermap.org/data/2.5/forecast?APPID=d89de3f0b2dedfe4f923f1e7f709953a&lat=${lat.toString()}&lon=${lon.toString()}');

      if (weatherResponse.statusCode == 200 &&
          forecastResponse.statusCode == 200) {
        return setState(() {
          weatherData =
              new WeatherData.fromJson(jsonDecode(weatherResponse.body));
          forecastData =
              new ForecastData.fromJson(jsonDecode(forecastResponse.body));
          isLoading = false;
        });
      }
    }

    setState(() {
      isLoading = false;
    });
  }
}

Weather.dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import 'package:uygulama1/WeatherData.dart';

class Weather extends StatelessWidget {
  final WeatherData weather;

  Weather({Key key, @required this.weather}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var temperature = (weather.temp - 273.15).round();
    return Column(
      children: <Widget>[
        Text(weather.name, style: new TextStyle(color: Colors.black)),
        Text("\n" + weather.main,
            style: new TextStyle(color: Colors.black, fontSize: 32.0)),
        Text("Temp: " + '${temperature.toString()}°C',
            style: new TextStyle(color: Colors.black)),
        Image.network('https://openweathermap.org/img/w/${weather.icon}.png'),
        Text("Date: " + new DateFormat.yMMMd().format(weather.date),
            style: new TextStyle(color: Colors.black)),
        Text("Hour: " + new DateFormat.Hm().format(weather.date),
            style: new TextStyle(color: Colors.black)),
      ],
    );
  }
}

其他文件实际上并不重要。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以创建一个地图,其中包含字符串(天气类型)和值为AssetImages的键,例如

final Map<String, AssetImage> images = {"rain": AssetImage("assets/rain.jpg"),
    "wind": AssetImage("assets/wind.jpg"),
    "snow": AssetImage("assets/snow.jpg")};

背景:

Container(
              decoration: BoxDecoration(
                image: new DecorationImage(
                  image: weatherData == null ? images["wind"] : images[weatherData.name],
                  fit: BoxFit.cover
                  ),
             ),
                  
        ),

假设:

  1. 在获取weatherData之前的默认背景是AssetImage("assets/wind.jpg")

  2. weatherData.name可以是“风” “雪” “雨”

答案 1 :(得分:0)

如果您有两个条件,也许可以这样做:

Container(
          decoration: BoxDecoration(
            image: new DecorationImage(
              image:
                     fit: BoxFit.cover,
                     (isRaining)? new AssetImage("assets/rain.jpg"):new AssetImage("assets/sunny.jpg")
               
              ),
              ),

如果您有多种情况,可以这样进行:

Container(
          decoration: BoxDecoration(
            image: new DecorationImage(
              image:
                     fit: BoxFit.cover,
                     if(isRaining) 
                       new AssetImage("assets/rain.jpg")
                     else if(isSunny)
                       new AssetImage("assets/sunny.jpg")
                     else
                       new AssetImage("assets/cold.jpg")

                     
              ),
              ),

希望这会有所帮助!快乐编码:)