我正在使用OpenWeatherMap的API开发一个天气应用程序。每次我尝试运行我的代码时,都会弹出错误延迟初始化。我尝试添加空安全检查(!)代替延迟,但它仍然是一样的。知道我可能出错的地方吗?任何帮助都将不胜感激。解决错误的示例代码将有很大帮助。谢谢!!
我在控制台中遇到的错误:
执行热重启…1,492毫秒在1,501毫秒内重新启动应用程序。异常被WIDGETS LIBRARY捕获 ╞═══════════════════════════════════════════════════════════ 以下LateError被抛出构建:LateLaunalizationError:字段“weatherInfo”尚未初始化。
注意:这只是控制台中错误的一部分,因为有很多。
UI守则:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'LastProject_model.dart';
class LastProjectScreen extends StatefulWidget {
const LastProjectScreen({Key? key}) : super(key: key);
@override
_LastProjectScreenState createState() => _LastProjectScreenState();
}
class _LastProjectScreenState extends State<LastProjectScreen> {
//initializing model class object
late WeatherInfo weatherInfo;
TextEditingController _textEditingController = TextEditingController();
//overriding initstate to parse the data and display it on the screen
@override
void initState() {
super.initState();
}
//data parsing function to call the data from the json file
getData() async {
http.Response jsondata = await http.get(Uri.parse(
'https://api.openweathermap.org/data/2.5/forecast/daily?q=${_textEditingController.text}&units=metric&cnt=7&appid=3c044b7295d2df14f8bee74c19d4b96f'));
print(jsondata.body);
weatherInfo = WeatherInfo.fromJson(json.decode(jsondata.body));
return weatherInfo;
}
//first row of the screen
Widget uirow1(WeatherInfo weatherInfo) {
return Container(
padding: EdgeInsets.all(5),
margin: EdgeInsets.only(left: 20, right: 20, top: 20),
decoration: BoxDecoration(
// color: Colors.white,
gradient: LinearGradient(
colors: [Colors.blue.shade200, Colors.blue.shade50]),
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3),
)
]),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
'name',
// weatherInfo.city.name,
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700),
),
SizedBox(height: 5),
Text('temp °F',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black)),
SizedBox(height: 5),
Text('description',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black))
],
),
Icon(
Icons.cloud,
color: Colors.pink[400],
size: 100,
),
],
),
);
}
//second row of the screen
Widget uirow2() {
return Container(
padding: EdgeInsets.all(5),
margin: EdgeInsets.all(20),
decoration: BoxDecoration(
// color: Colors.white,
gradient: LinearGradient(
colors: [Colors.blue.shade200, Colors.blue.shade50]),
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3),
)
]),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('windSpeed',
style: TextStyle(
fontSize: 15,
)),
// SizedBox(width: 3),
Text('humidity',
style: TextStyle(
fontSize: 15,
)),
// SizedBox(width: 5),
Text('°F',
style: TextStyle(
fontSize: 15,
)),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(Icons.air_outlined, color: Colors.grey[600], size: 25),
// const SizedBox(width: 5),
Icon(Icons.whatshot_rounded, color: Colors.grey[600], size: 25),
// const SizedBox(width: 5),
Icon(Icons.air_outlined, color: Colors.grey[600], size: 25)
],
),
],
),
);
}
//main body widget of the screen
Widget mainBodyWidget(BuildContext context) {
return
// ListView(scrollDirection: Axis.vertical, children: [
Container(
padding: EdgeInsets.all(15),
decoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSZCv1LyQUyAJQE21-uNUMx3S8ZgK2U9S--1wQB59QaTFHBp2VqxGTAen5FRA7m5h-E4OU&usqp=CAU'),
fit: BoxFit.fill)),
child: Column(
children: [
searchwidget(),
const SizedBox(height: 15),
uirow1(weatherInfo),
const SizedBox(height: 15),
uirow2(),
const SizedBox(height: 15),
uirow3()
],
),
);
}
//third row of the screen
Widget uirow3() {
return Container(
padding: EdgeInsets.all(15),
margin: EdgeInsets.only(left: 20, right: 20),
height: 180,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue.shade200, Colors.blue.shade50]),
borderRadius: BorderRadius.all(Radius.circular(20)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3),
)
]),
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext context, int index) {
return Container(
child: uirow3data(),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(width: 20);
},
itemCount: 7
// weatherInfo.weatherListInfo.length,
));
}
//data for the third row of the screen
Widget uirow3data() {
return Column(
children: [
Center(
child: Text('Saturday',
style: TextStyle(
fontWeight: FontWeight.bold,
))),
SizedBox(height: 5),
Icon(
Icons.cloud,
color: Colors.pink[400],
size: 50,
),
SizedBox(height: 4),
Text('High: 71°F'),
SizedBox(height: 3),
Text('Low: 71°F'),
SizedBox(height: 3),
Text('Hum: 40%'),
SizedBox(height: 3),
Text('Win: 4 mi/h')
],
);
}
//search textfiled widget
Widget searchwidget() {
return Container(
margin: EdgeInsets.only(left: 20, right: 20, top: 10),
child: Center(
child: TextField(
controller: _textEditingController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
gapPadding: 3.0,
borderSide: const BorderSide(color: Colors.grey, width: 2.0),
borderRadius: BorderRadius.circular(11)),
hintText: 'Search',
hintStyle: const TextStyle(color: Colors.grey),
prefixIcon: const Icon(
Icons.search_sharp,
color: Colors.grey,
),
suffixIcon: InkWell(
child: const Icon(Icons.navigate_next, color: Colors.grey),
onTap: () => getData(),
)),
),
),
);
}
//main container widget
Widget mainContainerWidget(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text("Couldn't load the data"));
}
if (snapshot.hasData) {
return Text("Data is being processed");
}
if (snapshot.data == null) {
return ListView.builder(
scrollDirection: Axis.vertical,
itemCount: 1,
shrinkWrap: true,
itemBuilder: (context, index) {
return Column(
children: [mainBodyWidget(context)],
);
});
}
return CircularProgressIndicator();
}));
}
//Main build function
@override
Widget build(BuildContext context) {
return mainContainerWidget(context);
}
}
模型类的代码:
class WeatherInfo {
late CityInfo city;
late String cod;
late double message;
late int cnt;
late List<WeatherListInfo> weatherListInfo;
WeatherInfo(
this.city, this.cod, this.message, this.cnt, this.weatherListInfo);
factory WeatherInfo.fromJson(Map<String, dynamic> json) {
return WeatherInfo(
CityInfo.fromJson(json["city"]),
json["cod"],
json["message"],
json["cnt"],
(json["list"] as List).map((e) => WeatherListInfo.fromJson(e)).toList());
}
}
class CityInfo {
late String id;
late String name;
late String country;
late String population;
late String timezone;
CityInfo(this.id, this.name, this.country, this.population, this.timezone);
factory CityInfo.fromJson(Map<String, dynamic> json) {
return CityInfo(json["id"].toString(), json["name"], json["country"],
json["population"].toString(), json["timezone"].toString());
}
}
class WeatherListInfo {
late String dt;
late String sunrise;
late String sunset;
late TemperatureListInfo temperatureListInfo;
late String pressure;
late String humidity;
late List<WeatherDetailInfo> weatherDetailInfo;
late FeelsLikeListInfo feelsLikeInfo;
late String speed;
late String deg;
late String gust;
late String clouds;
late String pop;
late String rain;
WeatherListInfo(
this.dt,
this.sunrise,
this.sunset,
this.temperatureListInfo,
this.pressure,
this.humidity,
this.weatherDetailInfo,
this.feelsLikeInfo,
this.speed,
this.deg,
this.gust,
this.clouds,
this.pop,
this.rain,
);
factory WeatherListInfo.fromJson(Map<String, dynamic> json) {
return WeatherListInfo(
json["dt"].toString(),
json["sunrise"].toString(),
json["sunset"].toString(),
TemperatureListInfo.fromJson(json["temp"]),
json["pressure"].toString(),
json["humidity"].toString(),
(json["weather"] as List).map((e) => WeatherDetailInfo.fromJson(e)).toList(),
FeelsLikeListInfo.fromJson(json["feels_like"]),
json["speed"].toString(),
json["deg"].toString(),
json["gust"].toString(),
json["clouds"].toString(),
json["pop"].toString(),
json["rain"].toString(),
);
}
}
class TemperatureListInfo {
late String day;
late String min;
late String max;
late String night;
late String eve;
late String morn;
TemperatureListInfo(
this.day, this.night, this.eve, this.morn, this.min, this.max);
factory TemperatureListInfo.fromJson(Map<String, dynamic> json) {
return TemperatureListInfo(
json["day"].toString(),
json["night"].toString(),
json["eve"].toString(),
json["morn"].toString(),
json["min"].toString(),
json["max"].toString(),
);
}
}
class FeelsLikeListInfo {
late String day;
late String night;
late String eve;
late String morn;
FeelsLikeListInfo(this.day, this.night, this.eve, this.morn);
factory FeelsLikeListInfo.fromJson(Map<String, dynamic> json) {
return FeelsLikeListInfo(
json["day"].toString(),
json["night"].toString(),
json["eve"].toString(),
json["morn"].toString(),
);
}
}
class WeatherDetailInfo {
late String id;
late String main;
late String description;
late String icon;
WeatherDetailInfo(this.id, this.main, this.description, this.icon);
factory WeatherDetailInfo.fromJson(Map<String, dynamic> json) {
return WeatherDetailInfo(
json["id"].toString(),
json["main"],
json["description"],
json["icon"],
);
}
}
错误消息说,你没有初始化weatherInfo
。当你将一个变量标记为late
时,你必须稍后初始化它,但是在你的情况下,你只有在调用getData()
时才初始化它,所以用户界面会抱怨,因为它使用了一个尚未初始化的变量。你必须在这里选择,
首先:您在initState
中调用getData
,因此变量将被初始化。
或者,第二:您删除了late
关键字并使对象可为空,但现在您必须在代码中添加null检查。