Future Builder not working with Geolocator with flutter
188
you need to return something try this
Future _getTown() async {
return address.first.locality;
}
also modify your builder
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
print(snapshot.data);
}
else{return loadingWidget();}
Author by
RyanBuss01
Updated on December 19, 2022Comments
-
RyanBuss01 over 1 year
I am a little new to flutter and I am using Geolocator plugin for the first time. I am trying to have a FutureBuilder that finds the city of the user when built but it never leaves the loading screen
this is my current code:
class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { String currentTown; @override Widget build(BuildContext context) { return FutureBuilder( future: _getTown(), builder: (context, snap) { if(snap.connectionState == ConnectionState.waiting) { return Loading(); } else { return Center( child: Text( currentTown ?? null, style: TextStyle( color: Colors.white ), ), ); } } ); } Future _getTown() async { print('get Town'); Position pos = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); final coordinates = Coordinates(pos.latitude, pos.longitude); var address = await Geocoder.local.findAddressesFromCoordinates(coordinates); print(address.first.locality); setState(() { currentTown = address.first.locality; }); } }
pubspec.yaml:
dependencies: geolocator: ^7.0.1 geocoder: ^0.2.1
I'm not exactly sure what I am doing wrong. I tried having the future return the String value but it still wouldn't change from the loading screen. even when I use ConnectionState it still doesn't work
-
RyanBuss01 about 3 yearsThank you so much I can't believe it was that simple I kinda feel like an idiot lol but thank you that fixed it for me :)
-
Dean Villamia about 3 yearsno worries we all have that moments haha :D