LateInitializationError: Field 'initialPosition' has not been initialized

1,510

The issue is occurring because initialPosition is null until the late initialization occurs, but it is being converted to a non-nullable type before the late initialization occurs here: mapViewModel.initialPosition!.

You can resolve this one of two ways.

  1. Return a default position if initialPosition is null when accessing it.
target: mapViewModel.initialPosition ?? [defaultPosition];
  1. Display a loading widget until initialPosition is initialized, then display GoogleMap.

Both of these solutions will require a minor state management solution in order to update the widget when initialPosition is finally initialized.

Share:
1,510
Try to Dev
Author by

Try to Dev

Updated on December 31, 2022

Comments

  • Try to Dev
    Try to Dev about 1 year

    I am trying to create map screen but I found the below error:

    ======== Exception caught by widgets library =======================================================
    The following LateError was thrown building Consumer<MapViewModel>(dirty, dependencies: [_InheritedProviderScope<MapViewModel>]):
    LateInitializationError: Field 'initialPosition' has not been initialized.
    
    The relevant error-causing widget was: 
      Consumer<MapViewModel> file:///Users/mahmoudalharoon/Desktop/Air%20Forces/aireforces/lib/screens/BaseScreen.dart:44:14
    When the exception was thrown, this was the stack: 
    #0      MapViewModel.initialPosition (package:airforces/screens/map/viewmodel/map_viewmodel.dart)
    #1      MapScreen.build.<anonymous closure> (package:airforces/screens/map/view/map_screen.dart:19:27)
    #2      Consumer.buildWithChild (package:provider/src/consumer.dart:180:19)
    #3      SingleChildStatelessWidget.build (package:nested/nested.dart:259:41)
    #4      StatelessElement.build (package:flutter/src/widgets/framework.dart:4648:28)
    ...
    ====================================================================================================
    

    and this is the below ViewModel I have:

    import 'package:airforces/enums/ScreenState.dart';
    import 'package:airforces/screens/BaseViewModel.dart';
    import 'package:geocoding/geocoding.dart';
    import 'package:geolocator/geolocator.dart';
    import 'package:google_maps_flutter/google_maps_flutter.dart';
    
    class MapViewModel extends BaseViewModel {
      late LatLng? initialPosition;
      late LatLng lastMapPosition = initialPosition!;
    
      void getUserLocation() async {
        Position position = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.high);
        List<Placemark> placemarks = await placemarkFromCoordinates(
            position.latitude, position.longitude);
        initialPosition = LatLng(position.latitude, position.longitude);
        print('${placemarks[0].name}');
        setState(ViewState.Idle);
      }
    }
    

    and this is the below map screen I have:

    import 'package:airforces/screens/BaseScreen.dart';
    import 'package:airforces/screens/map/viewmodel/map_viewmodel.dart';
    import 'package:flutter/material.dart';
    import 'package:google_maps_flutter/google_maps_flutter.dart';
    
    class MapScreen extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
        return BaseScreen<MapViewModel>(
          onFinish: (_) {
          },
          onModelReady: (mapViewModel) {
            mapViewModel.getUserLocation();
          },
          builder: (context, mapViewModel, child){
            return GoogleMap(
              initialCameraPosition: CameraPosition(
                target: mapViewModel.initialPosition!,
              ),
              myLocationEnabled: true,
            );
          },
        );
      }
    }