I'm on Flutter project and from the code below I retrieved the distance from the user's position and a fixed place.
But when I compile the code, the app shows Instance of 'Future<double>'
instead of distance but with print my console shows the distance:
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
)))
);
}
}
I cannot understand what is wrong.
Thank you.
CodePudding user response:
The are a couple of things.
distanceInMeters
is not aFuture
, so instead of using theawait
keyword before returning, you should return the double value fromgetCurrentLocation
like this:
return Future.value(distanceInMeters);
- This code:
final Future<void> position = getCurrentLocation();
is problematic, becausegetCurrentLocation()
has a type ofFuture<double>
. Normally you should use it like below, but this is abuild
function, where you are not allowed to useawait
, you can't mark thebuild
function asasync
.
final position = await getCurrentLocation();
- To solve your issue you could use a
FutureBuilder
, which will wait for the result ofgetCurrentLocation()
and build the widget once the future is completed. Please refer to the documentation for details (especially on how to create the future properly), but basically something like this:
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
});