如何在Flutter中按List <string>对List <type>进行排序

时间:2019-04-10 13:35:54

标签: android dart flutter

我要按属性attrlist的{​​{1}}值对列表进行排序,权重将类似于_weigth

weight='1',weight='2'....

3 个答案:

答案 0 :(得分:2)

我尝试了这段代码,它可以按您的意愿工作

class Attribute{

  String _attributerowid;
  String _grouprowid;
  String _attributename;
  String _weight;

  Attribute(this._attributerowid,this._grouprowid,this._attributename,this._weight);


  static List<Attribute> sort(List<Attribute> attributes){
    attributes.sort((a, b) => _compareAttributes(a, b));  
  }

  static int _compareAttributes(Attribute a, Attribute b) {
  if (a._weight != null && b._weight != null) {
    int aWeight = int.tryParse(a._weight);
    int bWeight = int.tryParse(b._weight);
    if (aWeight >= bWeight) {
      return 1;
    } else {
      return -1;
    }
  } else if (a._weight != null && b._weight == null) {
    return 1;
  } else if (a._weight == null && b._weight != null) {
    return -1;
  } else {
    return -1;
  }
}

}


void main(){
  Attribute a = Attribute('test','me','case','2');
  Attribute b = Attribute('test','me','case','1');
  Attribute c = Attribute('test','me','case','4');
  Attribute d = Attribute('test','me','case','3');
  List<Attribute> list= <Attribute>[a,b,c,d];
  Attribute.sort(list);
}

答案 1 :(得分:2)

这应该没事

_attrlist.sort((a, b) => {
  aWeight = int.tryParse(a._weight) ?? 0
  bWeight = int.tryParse(b._weight) ?? 0
  return aWeight.compareTo(bWeight);
})

答案 2 :(得分:1)

import 'package:queries/collections.dart';

void main() {
  var col = Collection(attrlist);
  var asc = col.orderBy((e) => int.tryParse(e._weight));
  print(asc.toList());
  var desc = col.orderByDescending((e) => int.tryParse(e._weight));
  print(desc.toList());
}

class Attribute {
  String _attributerowid;
  String _grouprowid;
  String _attributename;
  String _weight;

  String toString() {
    return '$_attributename weight: ${_weight}';
  }
}

List<Attribute> get attrlist => () {
      var result = <Attribute>[];
      for (var i = 0; i < 5; i++) {
        var attr = Attribute();
        attr._attributename = 'Attr ${4 - i}';
        attr._attributerowid = '0';
        attr._grouprowid = '0';
        attr._weight = '$i';
        result.add(attr);
      }

      return result;
    }();

结果:

[Attr 4 weight: 0, Attr 3 weight: 1, Attr 2 weight: 2, Attr 1 weight: 3, Attr 0 weight: 4] [Attr 0 weight: 4, Attr 1 weight: 3, Attr 2 weight: 2, Attr 3 weight: 1, Attr 4 weight: 0]