如何在获取 Flutter 中的当前位置时显示加载微调器?

How to display a loading spinner while getting the current location in Flutter?

我正在开发一个 Flutter 应用程序,它可以获取用户的当前位置,但是在获取位置时,它会显示这个 ugly red error screen(一旦获取位置就会消失)。

我想显示加载微调器或启动画面,而不是这个。我已将问题缩小到 initState():

期间调用的这个方法
void _setCurrentLocation() {
  Geolocator().getCurrentPosition().then((currLoc) {
    setState(() {
      currentLocation = currLoc;
    });
  });
}

还可以找到整个源文件here on GitHub

提前致谢!

使用FutureBuilder 小部件

在 initState 方法中调用您的 _setCurrentLocation 方法并将其分配给一个变量,例如 getLoc。

Future<Position> getLoc;

@override
void initState() {
// TODO: implement initState
getLoc = _setCurrentLocation();
super.initState();
}

使用 return 语句更改方法。

Future<Position> _setCurrentLocation() async {
var Location = await Geolocator().getCurrentPosition();
return Location;
}

将所有设计代码放入 futurebuilder 小部件

@override
Widget build(BuildContext context) {
return FutureBuilder(
    future: getLoc,
    builder: (context, data) {
      if (data.hasData) {
        return Text(data.data.toString());
      } else {
        return Center(child: CircularProgressIndicator());
      }
    });
}

使用小工具 Visibility()

bool _isLoading = false;

void _setCurrentLocation() {
  _isLoading = true;

  Geolocator().getCurrentPosition().then((currLoc) {
    setState(() {
      _isLoading = false;
      currentLocation = currLoc;
    });
  });
}

 return Scaffold(
      key: scaffoldKey,
      body: Container(
        child: Visibility(
         visible: _isLoading,
          child: Stack(
           children: <Widget>[
             GoogleMap( ...

          replacement: Container(
             child: CircularProgressIndicator(),
           ),

最简单的方法是使用条件渲染。 currentLocation 将为空,直到 _setCurrentLocation 将其设置为一个值。

class LocationDisplayPage extends StatefulWidget {
  @override
  _LocationDisplayPageState createState() => _LocationDisplayPageState();
}

class _LocationDisplayPageState extends State<LocationDisplayPage> {
  Position currentLocation;

  void _setCurrentLocation() {
    Geolocator().getCurrentPosition().then((currLoc) {
      setState(() {
        currentLocation = currLoc;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: currentLocation == null
            ? CircularProgressIndicator()
            : WidgetToRenderLocation(),
      ),
    );
  }
}