flutter - 如何解决此错误:LateInitializationError: Field 'weatherInfo' has not been initialized?
问题描述
我正在使用 OpenWeatherMap 的 API 开发天气应用程序。每次我尝试运行我的代码时,都会弹出延迟初始化的错误。我最近尝试添加空安全检查(!),但它仍然是一样的。知道我哪里可能出错了吗?任何帮助将不胜感激。解决错误的示例代码将有很大帮助。谢谢!!
我在控制台中遇到的错误:
正在执行热重启... 1,492ms 在 1,501ms 内重新启动应用程序。theftion trible tribrars捕获的例外╞═════════════════════════════════════════ ══════════════════ 构建时引发了以下LateError:LateInitializationError:字段'weatherInfo'尚未初始化。
抛出异常时,这是堆栈: C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/ internal/js_dev_runtime/private/ddc_runtime/errors.dart 251 :49 throw
packages/finalproject/LastProject/LastProject_Screen.dart 13:44 get weatherInfo packages/finalproject/LastProject/LastProject_Screen.dart 10:56 mainBodyWidget
packages/finalproject/LastProject/LastProject_Screen.dart 10:56 packages/flutter/src/widgets/sliver.dart 456:22 build packages/flutter/src/widgets/sliver.dart 1214:28 [_build]
packages/flutter/src/小部件/sliver.dart 1227:55 包/flutter/src/widgets/framework.dart 2573:19 buildScope
包/flutter/src/widgets/sliver.dart 1220:5 createChild
packages/flutter/src/rendering/sliver_multi_box_adaptor.dart 349:23 packages/flutter/src/scheduler/binding.dart 1080:9 handleDrawFrame packages/flutter/src/scheduler/binding.dart 863:7 C:/b/s/ w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19 internalCallback
注意:这只是控制台中的错误的一部分,因为有很多。
用户界面代码:
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()
,因此 ui 会抱怨,因为它使用了尚未初始化的变量。你必须在这里选择,
首先:您调用getData
,initState
因此变量将被初始化。
或者,第二个:您删除late
关键字并使对象可为空,但现在您必须在整个代码中添加空检查。
推荐阅读
- python - 如何在python中创建一个不返回控制的异步线程
- html - 我的愿望清单项目显示来源未知的问题
- telegram - 以用户身份发送 Telegram 消息
- c# - C#/ 视觉工作室 2019 || windows窗体自动滚动闪烁
- ios - 防止堆栈导航器在打开带有深层链接的本机应用程序时自动路由到屏幕
- python - 从rabbitMQ消费时,Flask消费者不执行回调
- python - 精度分数:比较训练数据与测试数据
- javascript - 如何对json数组值进行排序?
- java - 如何处理使用 KafkaAvroSerializer 序列化的记录的 Kafka 消费者反序列化错误?
- c# - .NET Core 提交将所有数据传递给控制器,除了 id