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!
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());
}
});
}
The simplest way is to use conditional rendering. currentLocation will be null until _setCurrentLocation set it to a value.
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(),
),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With