Home > Blockchain >  Field 'position' has not been initialized
Field 'position' has not been initialized

Time:11-04

I know it is a very common problem and a lot of people already asked for it, but I don't know what is wrong with my code

    @override
  void initState() {
    getUserPosition();
    super.initState();
  }

  void getUserPosition() async{
    Position positionTemp = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    setState((){
      position = positionTemp;
    });
  }

  @override
  Widget build(BuildContext context) {
    return FlutterMap(
      options: MapOptions(
        center: LatLng(position.latitude, position.longitude),
        zoom: 13.0,
      ),)}

The error is called in MapOptions when I need position.latitude and position.longitude

CodePudding user response:

You're not the first and you'll not be the last, but a little bit of research would help you: use FutureBuilder.

late final Future<Position> _init;

@override
void initState() {
  super.initState();
  _init = getUserPosition();
}

Future<Position> getUserPosition() async{
  return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}

@override
Widget build(BuildContext context) {
  return FutureBuilder<Position>(
    future: _init,
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) 
        // Return a widget to be shown while the position is being fetch
        return Center(child: CircularProgressIndicator());
   
      if (snapshot.hasError) 
        // Return a widget to be shown if an error ocurred while fetching
        return Text("${snapshot.error}");

      // You can access `position` here
      final Position position = snapshot.data!;
      return FlutterMap(
        options: MapOptions(
          center: LatLng(position.latitude, position.longitude),
          zoom: 13.0,
        )
      );
    }
  );
}

CodePudding user response:

I believe your problem is you are not waiting position to be initialized. To ensure position is initialized before the rest of the code I would do the following:

@override
void initState() {
  getUserPosition().then((positionTemp) {
    position = positionTemp;
    super.initState();
  });
}

Future<void> getUserPosition() async {
  Position positionTemp = await Geolocator.getCurrentPosition(desiredAccuracy: 
  LocationAccuracy.high);
}

In this code you call getUserPosition() and until its not finished (so positionTemp has a value, which after it's assigned to position) it doesn't continue.

  • Related