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;
});
}
}
天气.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
),
),
),
假设:
weatherData
获取is之前的默认背景AssetImage("assets/wind.jpg")
。weatherData.name
可以是“风”、“雪”和“雨”。
推荐阅读
- r - 如何计算所有可能波段组合中的归一化比率指数,然后与 R 中的环境变量相关?
- angular - ./src/polyfills.ts 中的错误未找到模块:错误:无法解析“zone.js/dist/zone”
- swift - 如何在 Swift 中测量 DispatchQueue 并发异步中的代码块执行时间?
- python - 在 Pyspark Rdd 映射函数中传递 python 类对象
- ruby-on-rails - 如何在 Ruby on rails 中创建动态哈希数组
- node.js - 如何将 1 存储为 Double mongoose,mongodb?
- assembly - 使用 SSE4.1 的 8 × 16 位整数向量的高效校验和
- javascript - 加载屏幕时如何将子属性/值传递给父组件
- java - 如何修复构建 Android 中的错误:使用未声明的标识符“V4L2_COM_CMD_FLUSH”
- reactjs - 移动屏幕,屏幕下方可见