我是新手,似乎无法对列表进行排序
flutter - 在列表上排序<dynamic>在比较器中变为动态而不是int-LMLPHP
图片中的代码:

_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;
    });
  }
与此代码,我收到此错误:[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是json解码的条目列表,如下所示:{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}我的目标是根据长度值订购列表。
困扰我的是事实,当我使用此代码:
conSites.sort((a, b) {
      var t1 = a['length'];
      var t2 = b['length'];(t2));
      print(t1.compareTo(t2));
      return 1;
    });
实际上返回 1 -1
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
所以,我该如何排序我的 list ?
哦,还有一个便条-这行得通:conSites[2]['length'].compareTo(conSites[3]['length']);,只是不在排序功能中。

最佳答案

您只需要清楚地说明,排序函数的返回值将返回int类型。可以通过将返回值强制转换为int来解决此错误。

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

关于flutter - 在列表上排序<dynamic>在比较器中变为动态而不是int,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63452258/

10-15 05:36