【发布时间】:2022-08-19 00:31:45
【问题描述】:
这是我的代码
import \'package:flutter/material.dart\';
import \'package:climate/services/location.dart\';
import \'package:http/http.dart\' as http;
import \'dart:convert\';
const apiKey = \'78c0a5319f932d3e171aa34ab51dd7e3\';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
late double latitude;
late double longitude;
@override
void initState() {
super.initState();
getLocation();
}
void getLocation() async {
Location location = Location();
await location.getCurrentLocation();
latitude = location.latitude;
longitude = location.longitude;
}
void getData() async {
http.Response reponse = await http.get(Uri.parse(
\"https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey\"));
if (reponse.statusCode == 200) {
String data = reponse.body;
int condition = jsonDecode(data)[\'weather\'][0][\'id\'];
print(condition);
double temp = jsonDecode(data)[\'main\'][\'temp\']; //main.temp
print(temp);
String city = jsonDecode(data)[\'name\']; //name
print(city);
} else {
print(reponse.statusCode);
}
print(reponse.body);
}
@override
Widget build(BuildContext context) {
getData();
return Scaffold();
}
}
问题是它说经度和纬度需要后期初始化,当我删除后期时,它会抛出一个错误,说需要初始化,请告诉我该怎么做。
我正在尝试使用颤振构建天气应用程序,但它一直抛出此错误,我尝试删除后期修饰符,但随后抛出错误说需要初始化。但如果我保留后期修饰符,它会显示 LateError (LateInitializationError: Field \'latitude\' has not been initialized.)
标签: flutter api initialization