Home > Mobile >  FlutterMap LateInitializationError State Management
FlutterMap LateInitializationError State Management

Time:02-11

I'm trying to make a Flutter app, using Riverpod for state management and FlutterMaps. I have set up notifiers for pages, and am also using a (State)NotifierProvider for the map page. I am building a search function, which goes to a search page which displays a list with search results. When one of these results (in a list) is clicked, I update the notifier of the map page. However, here comes the tricky part: I want to update the map according to the LatLng of the search result (center it).

My implementation of the Notifier contains: late MapController? _mapController;

My map page is loaded in and gets the mapController from the Notifier: mapController: notifier.getMapController()

Using Riverpod state management, this all should work, however I get the following Error:

LateError (LateInitializationError: Field '_state@1225051772' has already been initialized.)

This Error is within the MapController itself (which is part of the FlutterMaps package), so I do not want to touch that. Does anyone have any idea how to tackle this?

CodePudding user response:

you should remove the late keyword or you should intialise it in the initState method.

CodePudding user response:

lateerror is caused by nulling a variable that will fill before the application starts.

late MapController? _mapController;

this definition is wrong. Here, you are saying that this value will fill in soon. You also say that this value can be null.

late MapController _mapController;

if you do so this variable should not be null at runtime. if it is null you will get a lateerror error.

MapController? _mapController;

if you do it this way. This means that the value can be null. You should check when using. like this

void sameFunction(){
 if(_mapController!=null){
  ... your code
 // here make sure this variable is not null. For this reason ! i put this
  MapController anotherController=_mapController!;
}
}

or

 void sameFunction(){
  // Your code will not throw an error if this variable is null. Because specify that 
  //it can be null
     mapController?.moveTo(...)
    }

for more detailed information

  • Related