gpt4 book ai didi

flutter - LateError (LateInitializationError : Field 'latitude' has not been initialized.)

转载 作者:行者123 更新时间:2023-12-05 08:10:38 26 4
gpt4 key购买 nike

这是我的代码

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();
}
}

问题是它说经度和纬度需要延迟初始化,当我延迟删除时它会抛出一个错误,说需要初始化。

我正在尝试使用 flutter 构建一个天气应用程序,但它一直抛出此错误,我尝试删除 late 修饰符,但随后它抛出一个错误,指出需要初始化。但如果我保留 late 修饰符,它会显示 LateError:

LateInitializationError: Field 'latitude' has not been initialized

最佳答案

可空变量是您想要的,而不是延迟变量。要检查是否已初始化某些内容,您应该使用可为 null 的变量,并且您的代码已经设置好执行此操作。

改变

late MyData data;

MyData? data;

关于flutter - LateError (LateInitializationError : Field 'latitude' has not been initialized.),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72486833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com