Convert Future<int> to int in Flutter

10,539

Could also:

var dist =  await calculateDistance(list[i]);

It's gonna wait for the Future to return int value.

Another solution would be:

calculateDistance(list[i]).then((dist) {list[i].distance=dist;})

When Future is complete, then run function.

Share:
10,539
Fabio
Author by

Fabio

Still learning

Updated on December 15, 2022

Comments

  • Fabio
    Fabio over 1 year

    My goal is to sort a list of racks compared to the geo position of the user. Here's my code:

    import 'package:geolocator/geolocator.dart';
    import 'rack.dart';
    import 'dart:async';
    class RackList {
    
      List<Rack> _racks;
      RackList(this._racks);
      get racks => _racks;
    
      factory RackList.fromJson(Map<String,dynamic> json){
        var list = json['racks'] as List;
    
        Future<int> calculateDistance(var element) async{
          var startLatitude=45.532;
          var startLongitude=9.12246;
          var endLatitude=element.latitude;
          var endLongitude=element.longitude;
          var dist = await Geolocator().distanceBetween(
              startLatitude,
              startLongitude,
              endLatitude,
              endLongitude);
          var distance=(dist/1000).round();
          return distance;
        }
    
        list = list.map((i) => Rack.fromJson(i)).toList();
    
          for (int i = 0; i < list.length; i++) {
            var dist =  calculateDistance(list[i]);
            print(dist); //prints Instance of 'Future<int>'
            list[i].distance=dist; //crash
        }
    
        list.sort((a, b) => a.distance.compareTo(b.distance));
        return RackList(list);
      }
    }
    

    The problem is in the for cycle, the variable dist is a Future<int> type and cannot be assigned to list[i].distance. How can I convert that value to a normal int?

    I've tried the solution of @Nuts but:

    var distances = new List();
    for (int i = 0; i < list.length; i++) {
          calculateDistance(list[i]).then((dist) {
            distances.add(dist);
            print(distances[i]); //print the correct distance
          });
        }
    print("index 0 "+distances[0].toString()); //prints nothing
    

    It's like outside the for-cycle I lost all the values inside the distances list

  • Fabio
    Fabio over 4 years
    I've tried your solution but outside the for-cycle it's like the list is null.. print("index 0 "+distances[0].toString()); print nothing