Shubham_Kr
Shubham_Kr

Reputation: 1

LateInitializationError: Field currentPosition is not initialized - Flutter

I have been trying to make an application that will fetch a user's location and turn it into a local address. I don't understand the error here and how to solve it. The error : LateInitializationError: Field 'currentposition' has not been initialized.

I am trying to use the current position under the setState, to display the locality, sub-locality, street name and zip code, but even then the error is still thrown. I have defined it in the start, as String currentAddress = 'My Address'; late Position currentposition ;

I have attached the code below.
I am using Geolocator as a location service and Geocoding to translate that information to an address.

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';



class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  String currentAddress = 'My Address';
  late Position currentposition ;
  Future<Position?> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Fluttertoast.showToast(msg: 'Please enable Your Location Service');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Fluttertoast.showToast(msg: 'Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      Fluttertoast.showToast(
          msg:
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    try {
      List<Placemark> placemarks =
      await placemarkFromCoordinates(position.latitude, position.longitude);

      Placemark place = placemarks[0];

      setState(() {
        currentposition = position;
        currentAddress =
        "${place.locality}, ${place.subLocality},${place.street}, ${place.postalCode}";
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Location'),
      ),
      body: Center(
          child: Column(
            children: [
              Text(currentAddress),
              currentposition != null
                  ? Text('Latitude = ' + currentposition.latitude.toString())
                  : Container(),
              currentposition != null
                  ? Text('Longitude = ' + currentposition.longitude.toString())
                  : Container(),
              TextButton(
                  onPressed: () {
                    _determinePosition();
                  },
                  child: Text('Locate me'))
            ],
          ),),
    );
  }
}

Upvotes: 0

Views: 979

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63769

You are dealing with future and currentposition set under Future<Position?> _determinePosition(). Therefor, the value is reading before initialization. Use FutureBuilder to handle this situation.

 body:FutureBuilder(
            future: _determinePosition(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text("Error ");
              }else if(snapshot.hasData){
              .... return your widget

More about FutureBuilder

Upvotes: 1

Related Questions