英文:
flutter The instance member 'lat' can't be accessed in an initializer
问题
在我的Flutter 3中,我试图传递一个值,但它抛出一个错误,指示The instance member 'lat' can't be accessed in an initializer.。我从Flutter版本3以来就一直没有用Flutter了。我遇到的问题是我创建了一个初始化器:
late double lat;
late double long;
然后我在initState()方法中给它们赋值:
@override
void initState() async {
  // TODO: implement initState
  super.initState();
  Position position = await _determinePosition();
  lat = position.latitude;
  long = position.longitude;
}
final myCoordinates = Coordinates(lat, long); //这一行是错误的
当我尝试将lat和long传递给myCoordinates时,它抛出一个错误The instance member 'myCoordinates' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression。
我该如何传递这个值呢?
英文:
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?
答案1
得分: 1
你需要了解对象创建的顺序:
- 对象被创建
 - 所有最终成员变量被初始化
 - Flutter 将运行 initState
 
你需要在 initState 中初始化你的坐标:
@override
void initState() async {
  // TODO: implement initState
  super.initState();
  Position position = await _determinePosition();
  lat = position.latitude;
  lat = position.longitude;
  myCoordinates = Coordinates(lat, long); // 将初始化放在这里
}
final late myCoordinates;
英文:
You need to understand the order in which your object will be created:
- Object is created
 - All final member variables are initialized
 - 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;
答案2
得分: 0
将它标记为"late"可能会解决您的问题:
late final myCoordinates = Coordinates(lat, long);
英文:
Marking it late should probably solve it for you:
late final myCoordinates = Coordinates(lat, long);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论