我正在开发一个 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());
}
});
}
关于asynchronous - 如何在获取 Flutter 中的当前位置时显示加载微调器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58503797/