[英]Null value from a provider that return data after hot reload in flutter
由於提供程序返回空值,我打印了一個空值,並且我的小部件沒有按預期構建。 有趣的是,當我熱重新加載應用程序時,提供程序返回預期的值。 這個特定的提供者屬於 position 類型。 我正在使用地理定位器 api 來獲取用戶位置。 我曾嘗試使用安全的空返回,但沒有希望像這樣解決問題
@override
Widget build(BuildContext context) {
Position coordinates=Provider.of<Position>(context);
print(coordinates);
if(coordinates!=null){
.... some returned widget here...
}else{
return circularProgress();
}
}
}
該應用程序返回加載指示符circularProgress()
但當我熱重新加載時,返回前面的小部件。 我可能做錯了什么?
我正在使用位置插件,但我遇到了同樣的問題。 我正在分享我的解決方案。
class LocationRepository {
UserLocation userLocation;
Location location = Location();
Future<UserLocation> getCurrentLocation() async {
var currentLocation = await location.getLocation();
userLocation =
UserLocation(currentLocation.latitude, currentLocation.longitude);}
該類用於獲取用戶的第一個位置。 通過這種方式,當加載包含位置過程的頁面時,我有一個位置數據。
enum LocationProviderStatus {
Initial,
Loading,
Success,
Error,
}
我的提供者類中有枚舉。 我正在檢查數據是否加載。
Future<void> getLocation() async {
try {
_updateStatus(LocationProviderStatus.Loading);
_userLocation = await _locationRepository.getCurrentLocation()
_updateStatus(LocationProviderStatus.Success);
} catch{}
}
打開頁面時,調用此方法。
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 }
使用 Enum Status ,頁面等待它獲取位置數據。 如果您不想等待很長時間,可以設置超時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.