简体   繁体   中英

Can I sort List<dynamic> in dart

Can I sort List<dynamic> in dart?

List<dynamic> list= [9,10,'Plus One'];
list.sort();
print(list);

I expect the result like 9,10,'Plus One' Or 'Plus One', 9, 10

You just need to provide a callback to List.sort that orders heterogeneous types the wya you want. For example, assuming that your heterogeneous List contains only int s and String s, you could do:

  List<dynamic> list = [9, 10, 'Plus One'];
  list.sort((a, b) {
    if ((a is int && b is int) || (a is String && b is String)) {
      return a.compareTo(b);
    }

    if (a is int && b is String) {
      return -1;
    } else {
      assert(a is String && b is int);
      return 1;
    }
  });

  print(list);

If you need to potentially handle other types, you will need to adjust the callback appropriately.

If you want to sort dynamic list and want string before number(int or double) try

this code:

 List<dynamic> list = [
    'mahmoud',
    14,
    'zika',
    9,
    10,
    'plus One',
    5,
    'banana',
    1,
    2.5,
    'apple',
    2,
    1.2,
    'ball'
  ];
  list.sort(
    (a, b) {
      if ((a is num && b is num) || (a is String && b is String)) {
        return a.compareTo(b);
      }
      // a Greater than b return 1
      if (a is num && b is String) {
        return 1;
      }
      // b Greater than a return -1
      else if (a is String && b is num) {
        return -1;
      }
      // a equal b return 0
      return 0;
    },
  );
  print(list);// [apple, ball, banana, mahmoud, plus One, zika, 1, 1.2, 2, 2.5, 5, 9, 10, 14]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM