Home > Mobile >  Sorting map for key/value
Sorting map for key/value

Time:12-24

I have a `late Map<String, dynamic> datosSpots;

I am iterating datosSpots to update a key,value pair:

  value.docs.forEach((spot) {


    datosSpots = spot.data() as Map<String,dynamic>;

    GeoPoint spotLocation = datosSpots['location'];
    double latSpot = spotLocation.latitude;
    double lonSpot = spotLocation.longitude;

    //calculamos distancia
    double distancia = calculateDistance(
        widget.latitud, widget.longitud, latSpot, lonSpot);
    //actualizamos el valor de spot_distancia
    datosSpots.update("spot_distancia", (value) => distancia);
    print("distancia cambiada ${datosSpots['spot_distancia']}");
  });

Now I would like to sort updateDocs for key 'spot_distance'

CodePudding user response:

Use this example in order to sort the Map by its values, you would have to change the key to e1.spot_distance.compareTo(e2.spot_distance), and use the map variable that is intended to be sorted:

  Map map = {3: 'three', 1: 'one', 4: 'four', 2: 'two', 5: 'five'};

  var sortedMap = Map.fromEntries(
    map.entries.toList()
      ..sort(
        (e1, e2) => e1.value.compareTo(e2.value),
      ),
  );
  • Related