narrei
narrei

Reputation: 596

Sort on List<dynamic> gets dynamic instead of int in Comparator

i am new to flutter and seem to be unable to sort List

code 1

code from picture:

_getConSites(BuildContext context) async {
    var conSitesRes = await Network().getData('/con-sites');
    var conSites = json.decode(conSitesRes.body);

    conSites.forEach((cs) {
      if (cs['gpsx'] != null || cs['gpsy'] != null) {
        double xDiff = pow((location.latitude - cs['gpsx']).abs(), 2);
        double yDiff = pow((location.longitude - cs['gpsy']).abs(), 2);
        double length = sqrt(xDiff + yDiff);
        cs['length'] = length;
      } else {
        cs['length'] = 0;
      }
    });
    conSites.sort((a, b) {
      return a['length'].compareTo(b['length']);
    });
    // print(conSites);
    setState(() {
      this.conSites = conSites;
    });
  }

with this code, i am getting this error: [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: type '(dynamic, dynamic) => dynamic' is not a subtype of type '((dynamic, dynamic) => int)?' of 'compare'

conSites is json decoded list of entries like this: {id: 80, pseudo_id: 2019-04, name: xx Eurovea II, manager_id: 9, address: null, gpsx: 48.xxxx, gpsy: 17.xxxx, deleted_at: null, created_at: 2020-05-03T09:44:46.000000Z, updated_at: 2020-05-25T16:19:00.000000Z, length: 139.62085997829686}

my goal is to order list according to the length value.

what bugs me is the fact, that when i use this code:

conSites.sort((a, b) {
      var t1 = a['length'];
      var t2 = b['length'];(t2));
      print(t1.compareTo(t2));
      return 1;
    });

it actually returns 1s and -1s

I/flutter (11802): 1
I/flutter (11802): -1
I/flutter (11802): 1
I/chatty  (11802): uid=10133(com.example.koberaapp) 1.ui identical 1 line
I/flutter (11802): 1
I/flutter (11802): -1
I/flutter (11802): -1
I/flutter (11802): 1
I/flutter (11802): 1
I/flutter (11802): -1
I/flutter (11802): 1

so, how do i sort my list?

oh and also a side note - this worked: conSites[2]['length'].compareTo(conSites[3]['length']); , just not in the sort function.

Upvotes: 1

Views: 1202

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17141

You just need to make it clear to dart that the return value of your sorting function will return an int type. This error can be resolved by casting the return value to an int.

conSites.sort((a, b) {
  return a['length'].compareTo(b['length']) as int;
});

Upvotes: 4

Related Questions