I was trying to setup a mapController to return the bounds of Flutter_map but this "LateInitializationError: Field ‘_internalController@’ has not been initialized" error keeps coming up
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:dio_cache_interceptor_file_store/dio_cache_interceptor_file_store.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_cache/flutter_map_cache.dart';
import 'package:latlong2/latlong.dart';
import 'package:path_provider/path_provider.dart';
class CityMap extends StatefulWidget {
const CityMap({super.key});
@override
State<CityMap> createState() => _CityMapState();
}
class _CityMapState extends State<CityMap> with TickerProviderStateMixin {
final Future<CacheStore> _cacheStoreFuture = _getCacheStore();
static Future<CacheStore> _getCacheStore() async {
final dir = await getTemporaryDirectory();
return FileCacheStore('${dir.path}${Platform.pathSeparator}MapTiles');
}
var _mapController = MapController();
List<LatLng> markertram = [const LatLng(51.502762, -0.113125)];
List<Marker> buildMarker() {
List<Marker> markers = [];
LatLngBounds bounder = _mapController.camera.visibleBounds;
void createMarkers(
List<LatLng> positions, String metroNumber, List<String> polyLineIds) {
List<Marker> tramMarkers = positions.where((position) {
return bounder.contains(position);
}).map((position) {
return Marker(
width: 20.0,
height: 20.0,
point: position,
rotate: true,
alignment: Alignment.center,
child: GestureDetector(
onTap: () {},
child: Tooltip(
message: " Metro $metroNumber",
child: const Icon(Icons.tram_outlined),
),
),
);
}).toList();
markers.addAll(tramMarkers);
}
createMarkers(markertram, '2', ['tram2']);
return markers;
}
@override
void initState() {
super.initState();
_mapController = MapController();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<CacheStore>(
future: _cacheStoreFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
final cacheStore = snapshot.data!;
return Stack(
children: [
FlutterMap(
mapController: MapController(),
options: const MapOptions(
initialCenter: LatLng(51.515635, -0.092354),
initialZoom: 15.5,
maxZoom: 19.5,
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
tileProvider: CachedTileProvider(
store: cacheStore,
),
),
MarkerLayer(
markers: buildMarker(),
),
],
),
],
);
} else if (snapshot.hasError) {
return Center(child: Text(snapshot.error.toString()));
}
return const Center(child: CircularProgressIndicator());
},
));
}
}
Everywhere i look th solution seems to be setting the mapController in initstate but that didn’t work. but i also used futurebuilder to Delay Marker Rendering
2
Answers
Although the given answer did help fix the issue, I did encounter other problems down the line, and to avoid future issues, I ended up using the map controller with the provider, so it always initializes first, not to say this may not have its own issues as I currently only use it for map state.
The problem is like the error said, you use
MapController
to manage theFlutterMap
before theFlutterMap
rendered. There’s a mistakes that you can fix:_mapController
but you useMapController()
inFlutterMap
widget.buildMarker()
insideFlutterMap
This will caused an error because
FlutterMap
not rendered yet. There is an attributeonMapReady
inMapOptions
that provides this kind of case. My recommendation is to create new variable:Then in your
FlutterMap
option, fill_markerList
value inonMapReady
attribute:With this two fixes, your app will be fine.
Additional Minimal Reproducible Code
I provide additional minimal reproducible code for you to try out this solution, i made this based on your code with some modification but still same logic.
The output