Reputation: 427
Why the build method is showing 'NULL' at Restart, but update the Latitude value on hot-reload?
Is it possible to load the Text('Lat: $latitude') as initState() itself?
class _LoadingScreenState extends State<LoadingScreen> {
double latitude;
double longitude;
@override
void initState() {
super.initState();
getLocation();
}
void getLocation() async {
Location location = Location();
await location.getCurrentLocation();
latitude = location.latitude;
longitude = location.longitude;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(child: Text('Lat: $latitude')),
);
}
}
Upvotes: 0
Views: 219
Reputation: 116
as with the answer above, the getLocation is async meaning it will finish in future, on restart you get the current latitude which is null then as it didn't get the value yet, when hot reloading you get to show the value then which is already finished, you can use setState in stateful class as above, or you can use futurebuilder to show the value when available.
Upvotes: 0
Reputation: 8597
latitude
havn't had time to be assigned with a value when the build method is constructing the widget.
Wrap the assignment of latitude and longitude with the setState method to notify the framework that a new build should take place. That way the latitude value will be updated as soon as it is available.
setState(() {
latitude = location.latitude;
longitude = location.longitude;
});
A tip is to display something else instead of the latitude
value while waiting for it to be assigned. This could e.g. be a CircularProgressIndicator.
Upvotes: 1
Reputation: 2905
That's because you haven't called the setState
method when you changed your data, so the widget did not rebuild itself.
It should be like this:
void getLocation() async {
Location location = Location();
await location.getCurrentLocation();
setState(() {
latitude = location.latitude;
longitude = location.longitude;
});
}
Upvotes: 1