Urm*_*off 5 asynchronous future geolocation dart flutter
我正在开发一个 Flutter 应用程序,它获取用户的当前位置,但是在获取位置时,它显示了这个丑陋的红色错误屏幕(一旦获取位置,它就会消失)。
而不是这个,我想显示一个加载微调器或启动画面。我已将问题缩小到此期间调用的方法initState()
:
void _setCurrentLocation() {
Geolocator().getCurrentPosition().then((currLoc) {
setState(() {
currentLocation = currLoc;
});
});
}
Run Code Online (Sandbox Code Playgroud)
整个源文件也可以在 GitHub 上找到。
提前致谢!
使用FutureBuilder小部件
在 initState 方法中调用您的 _setCurrentLocation 方法并将其分配给一个变量,如 getLoc。
Future<Position> getLoc;
@override
void initState() {
// TODO: implement initState
getLoc = _setCurrentLocation();
super.initState();
}
Run Code Online (Sandbox Code Playgroud)
使用 return 语句更改您的方法。
Future<Position> _setCurrentLocation() async {
var Location = await Geolocator().getCurrentPosition();
return Location;
}
Run Code Online (Sandbox Code Playgroud)
将所有设计代码放入 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());
}
});
}
Run Code Online (Sandbox Code Playgroud)