Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 598
Urmil Shroff Avatar asked Oct 22 '19 11:10

Urmil Shroff


2 Answers

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());
      }
    });
}
like image 89
MSARKrish Avatar answered Nov 15 '22 09:11

MSARKrish


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(),
      ),
    );
  }
}
like image 27
Edwin Liu Avatar answered Nov 15 '22 11:11

Edwin Liu