I am getting a null printed and my widget not building as expected due to a null return from a provider. The funny thing is that when i hot reload the app the provider returns the value expected. This particular provider is of type position. i am using the geolocator api to get a users position. I have tried using a safe null return with no hope of solving the issue like so
@override
Widget build(BuildContext context) {
Position coordinates=Provider.of<Position>(context);
print(coordinates);
if(coordinates!=null){
.... some returned widget here...
}else{
return circularProgress();
}
}
}
The app returns the loading indicator circularProgress()
but when i hot reload, the preceeding widget is returned. What could i be doing wrong?
I am using location plugin but I had same issue. I am sharing my solution.
class LocationRepository {
UserLocation userLocation;
Location location = Location();
Future<UserLocation> getCurrentLocation() async {
var currentLocation = await location.getLocation();
userLocation =
UserLocation(currentLocation.latitude, currentLocation.longitude);}
The class is using for get first location of user. In this way I have a location data when page which include location process is loading.
enum LocationProviderStatus {
Initial,
Loading,
Success,
Error,
}
I have enum in my Provider Class. I am checking to data is loaded whether or not.
Future<void> getLocation() async {
try {
_updateStatus(LocationProviderStatus.Loading);
_userLocation = await _locationRepository.getCurrentLocation()
_updateStatus(LocationProviderStatus.Success);
} catch{}
}
When open the page, call this method.
class _LocationScreenState extends State<LocationScreen> {
Location location;
LocationData currentLocation;
@override
void initState() {
location = new Location();
location.onLocationChanged.listen((LocationData cLoc) {
currentLocation = cLoc;
});
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Consumer(builder: (context, LocationProvider provider, _) {
if (provider.status == LocationProviderStatus.Loading ||
provider.status == LocationProviderStatus.Initial) {
return Center(child: CircularProgressIndicator());
} else if (provider.status == LocationProviderStatus.Success) {
//your widget }
Using Enum Status , page is waiting until it gets location data. You can set a timeout if you don't want to wait for a long time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.