Farhana Naaz Ansari
Farhana Naaz Ansari

Reputation: 7944

How do I sort a List<Type> by List<String> in flutter

I want to sort attribute attrlist list by their _weigth value and weight will be like weight='1',weight='2'....

class Attribute{

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

}

List<Attribute> get attrlist => _attrlist;

Upvotes: 1

Views: 223

Answers (2)

dubace
dubace

Reputation: 1621

This should be fine

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

Upvotes: 2

Sami Kanafani
Sami Kanafani

Reputation: 15741

I tried this code and it is working as you like

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);
}

Upvotes: 2

Related Questions