How to display a loading spinner while getting the current location in Flutter?
15,543
Use FutureBuilder Widget
call your _setCurrentLocation method inside initState method and assign it to one variable like getLoc.
Future<Position> getLoc;
@override
void initState() {
// TODO: implement initState
getLoc = _setCurrentLocation();
super.initState();
}
Change your method with return statement.
Future<Position> _setCurrentLocation() async {
var Location = await Geolocator().getCurrentPosition();
return Location;
}
Put all your design code inside futurebuilder widget
@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());
}
});
}
Comments
-
Urmil Shroff almost 2 years
I'm working on a Flutter app which fetches the user's current location, but while the location is being fetched, it shows this ugly red error screen (which disappears once the location is fetched).
Instead of this, I'd like to display a loading spinner or splash screen. I've narrowed the problem down to this method that is called during
initState()
:void _setCurrentLocation() { Geolocator().getCurrentPosition().then((currLoc) { setState(() { currentLocation = currLoc; }); }); }
The entire source file can also be found here on GitHub.
Thanks in advance!