Home > Blockchain >  LateError (LateInitializationError: Field 'latitude' has not been initialized.)
LateError (LateInitializationError: Field 'latitude' has not been initialized.)

Time:06-03

Here's my code

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

The problem is it says the late initialization is required for longitude and latitude, and when I remove late it throws an error saying initialization is required please tell me what to do.

I am trying to build a weather application using flutter but it keeps on throwing this error, I tried removing the late modifier but then it throws an error saying initialization required. But if I keep the late modifier it says LateError (LateInitializationError: Field 'latitude' has not been initialized.)

CodePudding user response:

try this function

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

CodePudding user response:

A nullable variable is what you want, not a late variable. To check if something has been initialized, you should use a nullable variable, and your code is already set up to do so.

Just change

late MyData data;

to

MyData? data;
  • Related