所以我建立了我的第一个应用程序。这是一个天气应用程序。到目前为止,一切都按预期进行。但是有一个问题,每当我关闭应用程序然后重新打开它时,所有内容都为空(天气预报,位置名称,最高和最低温度)。当我按下刷新按钮时,它的null将更新为当前状态。我想做的是,我希望应用程序显示最后一次刷新并在按下刷新按钮时对其进行更新,而不是显示null。我怎样才能做到这一点。
请记住,我是新手。
main.dart:
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 description;
var city;
var maxTemp;
var minTemp;
var temp;
@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: 35,
color: Colors.white,
),
),
),
),
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: 100,
),
),
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),
),
),
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();
final currentTime = DateFormat.jm().format(now);
if (currentTime.contains('AM')) {
return 'images/Blood.png';
} else if (currentTime.contains('PM')) {
return 'images/Sun.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 {
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();
print(temp);
}
}
GetLocation.dart:
import 'package:geolocator/geolocator.dart';
class Getlocation {
double latitude;
double longitude;
var city;
//Get current location
Future<void> getCurrentLocation() async {
try {
Position position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
latitude = position.latitude;
longitude = position.longitude;
city = await getCityName(position.latitude, position.longitude);
} catch (e) {
print(e);
}
}
//Get city name
Future<String> getCityName(double lat, double lon) async {
List<Placemark> placemark =
await Geolocator().placemarkFromCoordinates(lat, lon);
print('city name is: ${placemark[0].locality}');
return placemark[0].locality;
}
}
答案 0 :(得分:0)
简便的解决方案是使用SharedPreferences,然后在刷新天气后将每个变量保存到其中,例如
Future<void> _saveStringInSharedPrefs(String key, String value) async =>
SharedPreferences.getInstance().then((prefs) => prefs.setString(key, value));
每个值的。您可能还想将var更改为类型,例如double,String等。
然后,您可以将initState添加到您的状态,在其中将每个变量设置为SharedPreferences.getString(variable_key)
。使用SharedPreferences prefs = SharedPreferences.getInstance()
然后调用prefs.getString()
会很方便,您可以在构建中添加它,但是您可能不应该这样做,因为构建方法本来应该是非常快的,所以它们最多可以运行60次/
编辑:
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);
await SharedPreferences.getInstance().then((prefs) {prefs.setString('weather_data', response.body}) // add this line
var dataDecoded = jsonDecode(response.body);
// (rest of the code)
这会将您的json保存到SharedPrefs。现在,您只需要提取与JSON一起使用的函数并设置变量即可。所以看起来像这样:
void _setData(String jsonString) {
var dataDecoded = jsonDecode(response.body);
description = dataDecoded['weather'][0]['description'];
// here it would be safer to have temp be of type 'int' instead of 'var' and set it like this:
// temp = dataDecoded['main']['temp'].toInt();
temp = dataDecoded['main']['temp'];
temp = temp.toInt();
maxTemp = dataDecoded['main']['temp_max'];
maxTemp = maxTemp.toInt();
minTemp = dataDecoded['main']['temp_min'];
minTemp = minTemp.toInt();
}
然后您可以像这样拆分getTemp:
Future<void> getTemp(double lat, double lon) async {
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);
_setData(response.body);
}
然后,当您启动应用程序时,您希望它从SharedPreferences中加载值。因此,将其添加到_AuraWeatherState:
@override
void initState() {
super.initState();
_loadData();
}
Future<void> _loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_setData(prefs.getString('weather_data'));
}
这应该可以,但是我没有时间检查它是否执行。因此,如果您还有其他疑问,我们将很乐意为您提供帮助:)