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

Viewed 561

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.)

3 Answers

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;

try this function

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

i've same error as you just i do these steps and it works for me

The code

1

it means when you open the app as already logged in user or new user ...the welcome screen is the first page for u both ...but i add a condition when a no logged in user wanna confirm his location he can't and a error notification (i made it with easyLoading (package from pub dev)) appear and materialPageRoute to welcomeScreen(); where he can registre or log in

Related