0

in my flutter 3 I'm trying to pass a a value, but it throws an error indicating The instance member 'lat' can't be accessed in an initializer.. i've been away from flutter since the version 3. the problem i'm having is I've created an initializer

late double lat;
late double long;

then i assigned the value in initState()

@override
  void initState() async {
    // TODO: implement initState
    super.initState();
    Position position = await _determinePosition();
    lat = position.latitude;
    lat = position.longitude;
  }

  final myCoordinates = Coordinates(lat, long); //this line is the error

when i try to pass the lat and long to mycoordinates it throws an error The instance member 'myCoordinates' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression.

How else can i pass this?

Mohammed Bekele
  • 727
  • 1
  • 9
  • 25

2 Answers2

1

You need to understand the order in which your object will be created:

  1. Object is created
  2. All final member variables are initialized
  3. Flutter will run initState

you need to put your initialize your coordinates in initState:

@override
  void initState() async {
    // TODO: implement initState
    super.initState();
    Position position = await _determinePosition();
    lat = position.latitude;
    lat = position.longitude;
    myCoordinates = Coordinates(lat, long); // move the initialization here
  }

  final late myCoordinates;
Andrija
  • 1,534
  • 3
  • 10
0

Marking it late should probably solve it for you:

late final myCoordinates = Coordinates(lat, long);
Ivo
  • 18,659
  • 2
  • 23
  • 35