skip to Main Content

I’m trying to fetch users coordinates with geolocator package. I’ve implemented a late initializer for coordinates type and assign value in initState. but whenever I use the late keyword it throws an error. but I assign a string for lat and long with late keyword, and it works fine.

  late String lat;
  late String long;
  late Coordinates coordinates;

   Future<Position> getCurrentLocation() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error("not enabled");
    }

    LocationPermission permission = await Geolocator.checkPermission();

    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error("permission denied");
      }
    }
    if (permission == LocationPermission.deniedForever) {
      return Future.error("ever denied");
    }

    return await Geolocator.getCurrentPosition();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getCurrentLocation().then((value) async {
      lat = "${value.latitude}";
      long = "${value.longitude}";

      List<Placemark> placemarks =
          await placemarkFromCoordinates(value.latitude, value.longitude);

      Placemark place = placemarks[0];

      String currentLocation = "${place.locality}, ${place.country}";

      final location = tz.getLocation(currentLocation);
      DateTime date = tz.TZDateTime.from(DateTime.now(), location);
      CalculationParameters params = CalculationMethod.MuslimWorldLeague();
      coordinates = Coordinates(value.latitude, value.longitude);

      setState(() {});
    });
  }

when I use lat or long in a text widget it displays the coordinates. but when I try to use coordinates.latitude it throws Flutter LateInitializationError: Field 'fieldname' has not been initialized error. it does the same thing when I try to assign a late initializer with such types. how can I fix this kind of problem?

3

Answers


  1. Don’t use late and give value for all parametre

    Login or Signup to reply.
  2. The getCurrentLocation is an async function, and this async function in the init function may set your lat long variable after the engine renders the UI. In your build function, you use the lat and long so it raises an error that the lat, long haven’t initialized yet. You should change from late to var for the lat and long, then the issue will be resolved.

    Login or Signup to reply.
  3. Use FutureBuilder and pass getCurrentLocation method as future parameter like this:

    import 'package:flutter/material.dart';
    import 'package:geolocator/geolocator.dart';
    import 'package:geocoding/geocoding.dart';
    
    class YourWidget extends StatefulWidget {
      @override
      _YourWidgetState createState() => _YourWidgetState();
    }
    
    class _YourWidgetState extends State<YourWidget> {
      Future<Position>? _locationFuture;
      late String lat;
      late String long;
      late Coordinates coordinates;
    
      Future<Position> getCurrentLocation() async {
        // Your existing implementation of getCurrentLocation() here
        // ...
      }
    
      @override
      void initState() {
        super.initState();
        _locationFuture = getCurrentLocation();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("Your App")),
          body: FutureBuilder<Position>(
            future: _locationFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(child: CircularProgressIndicator());
              } else if (snapshot.hasError) {
                return Center(child: Text("Error: ${snapshot.error}"));
              } else {
                final position = snapshot.data!;
                lat = "${position.latitude}";
                long = "${position.longitude}";
    
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("Latitude: $lat"),
                      Text("Longitude: $long"),
                      // You can now use 'coordinates.latitude' here without errors
                      // ...
                    ],
                  ),
                );
              }
            },
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search