我在 Flutter 專案中,從下面的代碼中檢索到用戶位置和固定位置的距離。
但是當我編譯代碼時,應用程式顯示Instance of 'Future<double>'的不是距離,而是列印我的控制臺顯示距離:
class ProductHorizontalListItem extends StatelessWidget {
const ProductHorizontalListItem({
Key? key,
required this.product,
required this.coreTagKey,
this.onTap,
}) : super(key: key);
final Product product;
final Function? onTap;
final String coreTagKey;
@override
Widget build(BuildContext context) {
// print('***Tag*** $coreTagKey${PsConst.HERO_TAG__IMAGE}');
final PsValueHolder valueHolder =
Provider.of<PsValueHolder>(context, listen: false);
Future<double> getCurrentLocation() async {
Position position = await Geolocator.getCurrentPosition();
double lat = position.latitude;
double long = position.longitude;
final double distanceInMeters = Geolocator.distanceBetween(
double.parse(position.latitude.toString()),
double.parse(position.longitude.toString()),
double.parse(product.itemLocation!.lat.toString()),
double.parse(product.itemLocation!.lng.toString()),
);
print(distanceInMeters);
return await distanceInMeters;
}
final Future<void> position = getCurrentLocation();
return InkWell(
onTap: onTap as void Function()?,
child: Container(
margin: const EdgeInsets.only(
left: PsDimens.space4, right: PsDimens.space4,
bottom: PsDimens.space12),
child: Text(
'${position}' '${product.itemLocation!.name}',
textAlign: TextAlign.start,
style: Theme.of(context).textTheme.caption!.copyWith(
color: PsColors.textColor3
)))
);
}
}
我無法理解出了什么問題。
謝謝你。
uj5u.com熱心網友回復:
有幾件事。
distanceInMeters不是 aFuture,因此不要await在回傳之前使用關鍵字,而應該getCurrentLocation像這樣回傳 double 值:
return Future.value(distanceInMeters);
- 這段代碼:
final Future<void> position = getCurrentLocation();有問題,因為getCurrentLocation()它的型別為Future<double>. 通常你應該像下面這樣使用它,但這是一個build函式,你不允許使用await,你不能將build函式標記為async。
final position = await getCurrentLocation();
- 要解決您的問題,您可以使用 a
FutureBuilder,它將等待結果getCurrentLocation()并在未來完成后構建小部件。請參閱檔案了解詳細資訊(尤其是關于如何正確創建未來),但基本上是這樣的:
return FutureBuilder<double>(
future: getCurrentLocation(),
builder: (BuildContext context, AsyncSnapshot<double> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
return InkWell(...); // use `snapshot.data` to get the double value
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/504121.html
上一篇:如何正確決議網址
