Flutter条件背景图像添加



我正在用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)),
],
);
}
}

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

谢谢你的帮助。

您可以拥有一个包含字符串键(天气类型(和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. CCD_ 4可以是";风";雪";雨

如果你有两个条件,你可以这样做:

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")

),
),

希望这能有所帮助!快乐编码:(

相关内容

  • 没有找到相关文章

最新更新