Search code examples
fluttergeolocator

flutter - LateInitializationError: Field 'currentPosition' has not been initialized


import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:kakao_map_plugin/kakao_map_plugin.dart';

class MapPage extends StatefulWidget {
  const MapPage({Key? key}) : super(key: key);

  @override
  State<MapPage> createState() => _MapPageState();
}

class _MapPageState extends State<MapPage> {
  late Position? currentPosition;
  late KakaoMapController _mapController;
  @override
  void initState() {
    super.initState();
    getCurrentLocation();
  }

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

      setState(() {
        currentPosition = position;
        print(currentPosition!.latitude);
        print(currentPosition!.longitude);
      });
    } catch (e) {
      print("Error getting current location: $e");
      // Handle error, show user a message, or fallback to a default location.
    }
  }

  @override
  Widget build(BuildContext context) {
    Set<Marker> markers = {};

    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          title: const Text('Map'),
        ),
        body: KakaoMap(
          onMapCreated: (controller) {
            setState(() {
              _mapController = controller;
              if (currentPosition != null) {
                _mapController.setCenter(
                  LatLng(currentPosition!.latitude, currentPosition!.longitude),
                );
              }
            });
          },
        ));
  }
}


This is the page of the map. I used kakao map, and I want to place the current location in the center of the map. I want to load the current location on the map into the middle of the Kakao map, but the error continues. Initialization is said to have failed. I'm very new to the flutter. Any advice on how to fix the code?


Solution

  • Just remove the late keyword from the position. So, change

    late Position? currentPosition;
    

    to

    Position? currentPosition;
    

    You are not allowed to access late variables while they are not initialized yet. And there's no point to make nullable variables late anyway