首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字段'position‘尚未初始化

字段'position‘尚未初始化
EN

Stack Overflow用户
提问于 2021-11-03 16:05:02
回答 2查看 26关注 0票数 1

我知道这是一个非常常见的问题,很多人已经要求它,但我不知道我的代码出了什么问题

代码语言:javascript
复制
    @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,
      ),)}

当我需要position.latitude和position.longitude时,在MapOptions中调用该错误

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-03 16:09:29

你不是第一个,也不会是最后一个,但稍微研究一下会对你有所帮助:使用FutureBuilder

代码语言:javascript
复制
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,
        )
      );
    }
  );
}
票数 0
EN

Stack Overflow用户

发布于 2021-11-03 16:47:32

我相信你的问题是你没有等待初始化的位置。为了确保position在其余代码之前被初始化,我将执行以下操作:

代码语言:javascript
复制
@override
void initState() {
  getUserPosition().then((positionTemp) {
    position = positionTemp;
    super.initState();
  });
}

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

在这段代码中,您调用getUserPosition(),直到它没有完成(所以positionTemp有一个值,在它被赋值给position之后),它不会继续。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69828118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档