Flutter 如何在构建有状态小部件之前等待函数?

Flutter 如何在构建有状态小部件之前等待函数?,flutter,dart,geolocation,Flutter,Dart,Geolocation,我正在等待GEOLOCATOR函数从用户那里获取位置。但是在初始构建过程中,我总是在从地理定位器实际检索位置之前几秒钟内收到一个错误(latitude被调用为null)。如何使位置在构建页面之前实际获取 import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; class DistancingPage extends StatefulWidget { DistancingPage

我正在等待GEOLOCATOR函数从用户那里获取位置。但是在初始构建过程中,我总是在从地理定位器实际检索位置之前几秒钟内收到一个错误(latitude被调用为null)。如何使位置在构建页面之前实际获取

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class DistancingPage extends StatefulWidget {
  DistancingPage(this.uid);
  @override
  _DistancingPageState createState() => _DistancingPageState();
}

class _DistancingPageState extends State<DistancingPage> {
Position position;

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

  Future<void> getPos() async {
    Position p = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    setState(() {
      position = p;
    });
  }
@override
  Widget build(BuildContext context) {
return Scaffold(
        appBar: AppBar(
          title: Text('Distancing Alerts'),
          backgroundColor: Colors.red[800],
),
body: Padding(
            padding: const EdgeInsets.all(36.0),
            child: Column(
              children: [
                Text(
                  'YOUR CURRENT POSITION',
                  style: TextStyle(
                    color: Colors.red[800],
                  ),
                ), //THE ERROR OCCURS HERE
                Text(position.latitude.toString() +
                    '° N , ' +
                    position.longitude.toString() +
                    '° E'),
],
            )));
  }
}


导入“包装:颤振/材料.省道”;
导入“包:地理定位器/地理定位器.dart”;
类距离页扩展StatefulWidget{
距离页面(this.uid);
@凌驾
_DistancingPageState createState()=>\u DistancingPageState();
}
类_DistancingPageState扩展状态{
位置;
@凌驾
void initState(){
super.initState();
getPos();
}
Future getPos()异步{
位置p=等待地理定位器。getCurrentPosition(
所需精度:定位精度高);
设置状态(){
位置=p;
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“距离警报”),
背景颜色:颜色。红色[800],
),
主体:填充物(
填充:常数边集全部(36.0),
子:列(
儿童:[
正文(
“你目前的职位”,
样式:TextStyle(
颜色:颜色。红色[800],
),
),//此处发生错误
文本(position.latitude.toString()+
“°N”+
position.longitude.toString()+
"E",,
],
)));
}
}

您应该使用
FutureBuilder
小部件,其中future是您的异步函数,builder是您想要返回的任何内容(您的示例中的scaffold)。使用snapshot.hasData检查future是否返回了任何内容,如果没有返回任何内容,则返回进度指示器(或任何您想要的内容)

    FutureBuilder(
      future: getPos(),
      builder: (context, snapshot) {
    snapshot.hasData ? 
      Scaffold(
                appBar: AppBar(
                  title: Text('Distancing Alerts'),
                  backgroundColor: Colors.red[800],
        ),
        body: Padding(
                    padding: const EdgeInsets.all(36.0),
                    child: Column(
                      children: [
                        Text(
                          'YOUR CURRENT POSITION',
                          style: TextStyle(
                            color: Colors.red[800],
                          ),
                        ), //THE ERROR OCCURS HERE
                        Text(position.latitude.toString() +
                            '° N , ' +
                            position.longitude.toString() +
                            '° E'),
        ],
                    ))) : CircularProgressIndicator();};

您应该使用
FutureBuilder
小部件,其中future是您的异步函数,而builder是您想要返回的任何东西(在您的例子中是scaffold)。使用snapshot.hasData检查future是否返回了任何内容,如果没有返回任何内容,则返回进度指示器(或任何您想要的内容)

    FutureBuilder(
      future: getPos(),
      builder: (context, snapshot) {
    snapshot.hasData ? 
      Scaffold(
                appBar: AppBar(
                  title: Text('Distancing Alerts'),
                  backgroundColor: Colors.red[800],
        ),
        body: Padding(
                    padding: const EdgeInsets.all(36.0),
                    child: Column(
                      children: [
                        Text(
                          'YOUR CURRENT POSITION',
                          style: TextStyle(
                            color: Colors.red[800],
                          ),
                        ), //THE ERROR OCCURS HERE
                        Text(position.latitude.toString() +
                            '° N , ' +
                            position.longitude.toString() +
                            '° E'),
        ],
                    ))) : CircularProgressIndicator();};

您可以从Flatter_spinkit添加带有一些动画的临时页面。在该页面上,您正在等待地理定位器功能,当它返回一个值时,您将导航到主屏幕

,您可以添加一个临时页面,其中包含来自Flatter_spinkit的一些动画。在该页面上,您正在等待地理定位器功能,当它返回一个值时,您将导航到主屏幕

,或者如果应用程序位于前台,您可以从后台获取位置,如果应用程序位于前台,有文章如何做,或者您可以从后台获取位置,如果应用程序位于前台,有文章如何做,您不能这样做,在构建UI时,您不能等待未来,但可以在数据可用后更新UI,为此使用FutureBuilder。您不能在构建UI时等待未来,但可以在数据可用后更新UI,为此使用FutureBuilder