skip to Main Content

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?

2

Answers


  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;
    
    Login or Signup to reply.
  2. Marking it late should probably solve it for you:

    late final myCoordinates = Coordinates(lat, long);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search