美文网首页Flutter圈子Flutter中文社区Flutter
Flutter 中List<dynamic>中数据排

Flutter 中List<dynamic>中数据排

作者: Scott昵称被占用 | 来源:发表于2019-07-24 00:50 被阅读5次

在我们做App中列表时少不了进行数据排序,比如城市列表等等,再Flutter中List是怎么排序的呢,Flutter的框架基础是Dart所以我们还是要回归Dart

先给大家看效果吧


效果图

官方介绍

void sort([int compare(E a, E b)]);
/**
   * Sorts this list according to the order specified by the [compare] function.
   *
   * The [compare] function must act as a [Comparator].
   *
   *     List<String> numbers = ['two', 'three', 'four'];
   *     // Sort from shortest to longest.
   *     numbers.sort((a, b) => a.length.compareTo(b.length));
   *     print(numbers);  // [two, four, three]
   *
   * The default List implementations use [Comparable.compare] if
   * [compare] is omitted.
   *
   *     List<int> nums = [13, 2, -11];
   *     nums.sort();
   *     print(nums);  // [-11, 2, 13]
   *
   * A [Comparator] may compare objects as equal (return zero), even if they
   * are distinct objects.
   * The sort function is not guaranteed to be stable, so distinct objects
   * that compare as equal may occur in any order in the result:
   *
   *     List<String> numbers = ['one', 'two', 'three', 'four'];
   *     numbers.sort((a, b) => a.length.compareTo(b.length));
   *     print(numbers);  // [one, two, four, three] OR [two, one, four, three]
   */

官方路径:https://api.dartlang.org/stable/2.4.0/dart-core/List/sort.html

所以对于List<dynamic> 进行排序的结果如下

List<dynamic> brands = List<dynamic>.from(val.data);
brands.sort((ak, bk) {
    /**
      我的dynamic是{key:value},这种结构, 所以使用了Map,如果List中是String,可以直接codeUnits
 关于 codeUnits:返回此字符串的UTF-16代码单元的不可修改列表。
[https://api.dartlang.org/stable/2.4.0/dart-core/String/codeUnits.html](https://api.dartlang.org/stable/2.4.0/dart-core/String/codeUnits.html)
   **/
    Map<String,dynamic> aj = Map<String,dynamic>.from(ak); 
    Map<String,dynamic> bj = Map<String,dynamic>.from(bk);
    List<int> al = '${aj['brand_en']}'.codeUnits;
    List<int> bl =  '${bj['brand_en']}'.codeUnits;
    for (int i = 0; i < al.length; i++) {
              if (bl.length <= i) return 1;
              if (al[i] > bl[i]) {
                return 1;
              } else if (al[i] < bl[i]) return -1;
            }
            return 0;
          });

codeUnits:https://api.dartlang.org/stable/2.4.0/dart-core/String/codeUnits.html

蜂产品之健康

相关文章

网友评论

    本文标题:Flutter 中List<dynamic>中数据排

    本文链接:https://www.haomeiwen.com/subject/kvazlctx.html