You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter LateInitializationError求助:已初始化仍触发报错

Flutter获取OpenWeather API数据时遇到LateInitializationError问题

我是编程新手,正在Udemy上Angela Yu的Flutter课程学习Flutter/Dart,目前学到第148讲——从OpenWeather API获取真实天气数据。

目标

我的代码应返回纬度、经度以及城市名称(例如285.7, 803, Cupertino)。

问题

遇到LateInitializationError报错(错误信息如下),但我认为已经完成了变量初始化。尝试使用可空类型(double? latitudeLocation; double? longitudeLocation; double? latitude; double? longitude;),但打印时变量为空,还会触发HTTP 400错误。

错误信息

E/flutter ( 5529): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: LateInitializationError: Field 'latitudeLocation' has not been initialized.
E/flutter ( 5529): #0 Location.latitudeLocation (package:clima_flutter_master/services/location.dart)
E/flutter ( 5529): #1 _LoadingScreenState.getLocation (package:clima_flutter_master/screens/loading_screen.dart:23:25)

环境与代码

flutter sdk: 2.17.6

main.dart

import 'package:flutter/material.dart';
import 'package:clima_flutter_master/screens/loading_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

loading_screen.dart

import 'package:clima_flutter_master/services/location.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

const apiKey = 'a89551623de7f2e030c199c9ec9ae123';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  late double latitude;
  late double longitude;

  void getLocation() async {
    Location location = Location();
    await location.getCurrentLocation;

    latitude = location.latitudeLocation;
    longitude = location.longitudeLocation;

    getData();
  }

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  void getData() async {
    http.Response response = await http.get(Uri.parse(
        'https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey'));
    print(response.statusCode);

    if (response.statusCode == 200) {
      String data = response.body;
      print(data);

      var decodedData = jsonDecode(data);

      double temperature = decodedData(data)['main']['temp'];
      print(temperature);

      int condition = decodedData['weather'][0]['id'];
      print(condition);

      String cityName = decodedData['name'];
      print(cityName);
    } else {
      print(response.statusCode);
    }
  }

  @override
  Widget build(BuildContext context) {
    getData();
    return Scaffold();
  }
}

location.dart

import 'package:geolocator/geolocator.dart';

class Location {
  late double latitudeLocation;
  late double longitudeLocation;

  Future<void> getCurrentLocation() async {
    try {
      Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.low);

      latitudeLocation = position.latitude;
      longitudeLocation = position.longitude;
    } catch (error) {
      print(error);
    }
  }

  void getLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }
  }
}

感谢各位的帮助!

内容的提问来源于stack exchange,提问作者Wilhelm77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:05:22