【问题标题】:LateError (LateInitializationError: Field 'latitude' has not been initialized.)LateError(LateInitializationError:字段\'latitude\'尚未初始化。)
【发布时间】: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


    【解决方案1】:

    可以为空的变量是您想要的,而不是后期变量。要检查是否已初始化某些内容,您应该使用可为空的变量,并且您的代码已经设置为这样做。

    只是改变

    late MyData data;
    

    MyData? data;
    

    【讨论】:

    • 我用晚期双纬取代了晚期双纬?纬度但仍然出现同样的错误,如果我做错了,请告诉我,因为我仍然遇到同样的错误
    • 像这样。双倍的?纬度;双倍的?经度;
    【解决方案2】:

    试试这个功能

      void getLocation() async {
        Location location = Location();
        await location.getCurrentLocation();
        setState(() {
          latitude = location.latitude;
          longitude = location.longitude;
        });
      }
    

    【讨论】:

    • 仍然得到同样的错误
    • 最好对您的代码进行一些解释,而不是仅“尝试一下”。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案3】:

    我和你有同样的错误,我只是做了这些步骤,它对我有用

    编码

    这意味着当您以已登录用户或新用户的身份打开应用程序时...欢迎屏幕是你们俩的第一页...但是当没有登录的用户想要确认他的位置时,我添加了一个条件他不能并且出现错误通知(我使用easyLoading(来自pub dev的包)),并且materialPageRoute到welcomeScreen();他可以在哪里注册或登录
    我希望它有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2021-10-27
      • 2021-12-29
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多