gpt4 book ai didi

flutter - flutter 条件背景图像添加

转载 作者:行者123 更新时间:2023-12-03 03:32:19 24 4
gpt4 key购买 nike

我正在使用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;
});
}
}
风标
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值的 map ,例如

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之前的默认背景是AssetImage("assets/wind.jpg")
  • weatherData.name可以是“风”,“雪”和“雨”。
  • 关于flutter - flutter 条件背景图像添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63230744/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com