Я пытаюсь создать погодное приложение. Я получаю данные о погоде с карты Openweather. Как вы увидите в последнем методе, я использую fromMillisecondsSinceEpoch для преобразования отметки времени Unix, получаемой с карты Openweather, во время и дату. Отметки времени Unix представляют восход и закат.
Проблема в том, что когда я закрываю приложение или когда выполняю горячий перезапуск или перезагрузку приложения, я получаю сообщение об ошибке (я указал ошибку ниже). И затем, когда я снова перезагружаю приложение, оно начинает работать нормально, горячая перезагрузка - единственное, что заставляет его снова работать.
Я не использую fromMicrosecondsSinceEpoch, потому что он преобразует отметки времени Unix во время и дату, но это время и дата равны 50 годам go.
Код:
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.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 weatherIcon;
var description;
var maxTemp;
var minTemp;
var format_sunRise;
var sunRise;
var format_sunSet;
var format_sunRiseEnd;
var format_sunSetEnd;
var sunSet;
var temp;
var city;
var dataDecoded;
var latitude;
var longitude;
@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: 25,
color: Colors.white,
fontFamily: 'Roboto',
),
),
),
),
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: 20),
child: Icon(
getWeatherIcon(),
size: 100,
color: Colors.white,
),
),
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,
fontFamily: 'Roboto mono',
),
),
),
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();
var currentTime = DateFormat.jm().format(now);
DateFormat midNight = new DateFormat.Hm();
DateTime midNightTime = midNight.parse("10:30");
midNightTime = new DateTime(
now.year, now.month, now.day, midNightTime.hour, midNightTime.minute);
if (currentTime.contains('AM')) {
return 'images/Blood.png';
} else if (currentTime.contains('PM')) {
return 'images/sunSet.jpg';
}
/*if (now.isBefore(format_sunRise)){
return 'images/night.jpg';
}else if(now.isAfter(format_sunRise) && (now.isBefore(format_sunRiseEnd))){
return 'images/sunRise.jpg';
}else if((format_sunRiseEnd) && (now.isBefore(format_sunSet))){
return 'images/day.jpg';
}else if((now.isAfter(format_sunSet)) && (now.isBefore(format_sunRiseEnd))){
return 'images/sunSet.jpg';
}else if((now.isAfter(format_sunRiseEnd)) && (now.isBefore(midNightTime))){
return 'images/night.jpg';
}*/
}
getWeatherIcon() {
var now = DateTime.now();
var currentTime = DateFormat.jm().format(now);
DateFormat midNight = new DateFormat.Hm();
DateTime midNightTime = midNight.parse("23:59");
midNightTime = new DateTime(
now.year, now.month, now.day, midNightTime.hour, midNightTime.minute);
if (now.isBefore(format_sunRise)) {
return FontAwesomeIcons.moon;
} else if (now.isAfter(format_sunRise) &&
(now.isBefore(format_sunRiseEnd))) {
return FontAwesomeIcons.solidSun;
} else if ((format_sunRiseEnd) && (now.isBefore(format_sunSet))) {
return FontAwesomeIcons.cloudRain;
} else if ((now.isAfter(format_sunSet)) &&
(now.isBefore(format_sunRiseEnd))) {
return FontAwesomeIcons.snowflake;
} else if ((now.isAfter(format_sunRiseEnd)) &&
(now.isBefore(midNightTime))) {
return FontAwesomeIcons.cloudMoonRain;
}
}
//getLocation
void getLocation() async {
Getlocation getlocation = Getlocation();
await getlocation.getCurrentLocation();
latitude = getlocation.latitude;
print(latitude);
longitude = getlocation.longitude;
print(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=$latitude&lon=$longitude&appid=$apiKey&units=metric');
//print(response.body);
dataDecoded = jsonDecode(response.body);
description = dataDecoded['weather'][0]['description'];
temp = dataDecoded['main']['temp'].toInt();
maxTemp = dataDecoded['main']['temp_max'].toInt();
minTemp = dataDecoded['main']['temp_min'].toInt();
sunRise = dataDecoded['sys']['sunrise'];
format_sunRise = DateTime.fromMillisecondsSinceEpoch(sunRise * 1000);
format_sunRiseEnd = format_sunRise.add(Duration(hours: 1));
sunSet = dataDecoded['sys']['sunset'];
format_sunSet = DateTime.fromMillisecondsSinceEpoch(sunSet * 1000);
format_sunSetEnd = format_sunSet.add(Duration(hours: 1));
print('Current temp: $temp');
print('Max temp: $maxTemp');
print('Min temp: $minTemp');
print('Sunrise time: $format_sunRise');
print('Sunset time: $format_sunSet');
}
}
Я получаю ошибку:
Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building AuraWeather(dirty, state: _AuraWeatherState#59e2b):
The getter 'microsecondsSinceEpoch' was called on null.
Receiver: null
Tried calling: microsecondsSinceEpoch
The relevant error-causing widget was:
AuraWeather file:///C:/Users/aldo0/Desktop/Learn_Flutter/aura_weather/lib/main.dart:12:10
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 DateTime.isBefore (dart:core-patch/date_patch.dart:84:51)
#2 _AuraWeatherState.getWeatherIcon (package:com/main.dart:183:13)
#3 _AuraWeatherState.build (package:com/main.dart:96:23)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
Как я уже сказал выше, момент Я перезагружаю приложение, оно снова работает. а затем, когда я перезагружаю его снова, я снова получаю эту ошибку. Это раздражает. В настоящее время приложение невозможно использовать на физическом устройстве, потому что оно запускается с красным экраном ошибки, сообщающим: «Получатель 'microsecondsSinceEpoch' был вызван с нулевым значением».
Спасибо за помощь.