Flutter - FutureBuilder sometimes gives me null distance on list of items

Viewed 59

I get a list of items in home of my app. In each one of this items I show the distance from the user and the item.

But in some item I have the distance and in others get null

enter image description here

This is my partial code:

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()),
          );

            return Future.value(distanceInMeters);

        }

        return FutureBuilder<double>(
                future: getCurrentLocation(),
            builder: (BuildContext context, AsyncSnapshot<double> snapshot) {
        return InkWell(
        onTap: onTap as void Function()?,
        child: Container(
            margin: const EdgeInsets.only(
                left: PsDimens.space4, right: PsDimens.space4,
                bottom: PsDimens.space12),
            child: Text(
                '${snapshot.data}',
                textAlign: TextAlign.start,
                style: Theme.of(context).textTheme.caption!.copyWith(
                    color: PsColors.textColor3
                )))

        );});
  }
}

Somebody can tell me why?

Thank you.

1 Answers

In the FutureBuilder you need to handle the different statuses of the future. With your current code you are building the widget on the very first snapshot. The reason of the null values is likely this, in most of the cases (if not every time) the first snapshot will not contain valid value.

Look at the following code about how to handle the different cases in a FutureBuilder:

return FutureBuilder<double>(
  future: getCurrentLocation(),
  builder: (BuildContext context, AsyncSnapshot<double> snapshot) {

    // the future is not completed yet, so show a progress indicator
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    }

    // the future is completed, but with an error, you have to handle it
    if (snapshot.hasError) {
      return...;
    }

    // the future is completed without error, but still you need
    // to check whether it contains data, this is basically a check
    // against null
    if (snapshot.hasData) {
      return...;
    }

    // if your code arrives here, it means the future is already
    // completed, there was no error but the data returned is null
    return...;
  });
Related