Home > Net >  Reorder Array of objects Flutter
Reorder Array of objects Flutter

Time:11-24

Array of object

Input:

[
 {id:1,order:1},
 {id:2,order:null},
 {id:3,order:0},
 {id:4,order:null},
 {id:5,order:3}
]

Output:

[
 {id:3,order:0},
 {id:1,order:1},
 {id:2,order:null},
 {id:5,order:3},
 {id:4,order:null}
]

Considering model

Item(int id,int? Order)

By default the order is null and these positions are to be maintained and object having orders are to be moved up or down.

CodePudding user response:

Try this, if the array is of type Map -

arrayOfObjects.sort((a, b) => a['order'].compareTo(b['order']));

Or this if it is holding Item class with an order attribute

arrayOfObjects.sort((Item a, Item b) => a.order.compareTo(b.order));

Note - You can remove items with null order before running the sort.

Example

arrayOfObjects.removeWhere((item)=> item.order == null);

CodePudding user response:

The double Iterations are based on the length of the array to handle the nulls. Solution

import 'package:collection/collection.dart';

class Item {
   int? _id;
   int? _order;

  Item({int? id, int? order}) {
    this._id = id;
     this._order = order;
  }

  int? get id => _id;
  set id(int? id) => _id = id;
  int? get order => _order;
  set order(int? order) => _order = order;

  Item.fromJson(Map<String, dynamic> json) {
    _id = json['id'];
   _order = json['order'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this._id;
    data['order'] = this._order;
    return data;
  }
}


List<Item> reorder(List<Item> it){

  var tempData = it;
  tempData.forEach((_){
  tempData.forEachIndexed((index,val){
  ///Remove original and replace
   var ind = val.order;
  if(ind!=null){
  
   ///Check if it is at the Proper Position
    if (index == ind) {
      return;
    }

     var first = it.removeAt(index);
     it.insert(ind as int, first);
  }
    
  });
 });

  return it; 
}

void main() {
  var list = [
    Item(id: 1, order: 1),
    Item(id: 3, order: 2),
    Item(id: 2, order: 7),
    Item(id: 4, order: null),
    Item(id: 5, order: null),
    Item(id: 6, order: null),
    Item(id: 7, order: 6),
  Item(id: 8, order: 4)
  ];

  list.forEach((it) => print('${it.id} ->${it.order}'));


  var first = reorder(list);


  print('\n');
  first.forEach((it) => print('${it.id} ->${it.order}'));
  ///Stack List
}
  • Related