Home > Back-end >  Flutter orderby json data
Flutter orderby json data

Time:10-08

I have data like:

[
    {name: Imamat, short_name: Lev, chapters: 27, name_en: Leviticus, type: old, order: 3},
    {name: Kejadian, short_name: Gen, chapters: 50, name_en: Genesis, type: old, order: 1},
    //....
]

I need to return this data sorted by order value like 1,2,3,4,.... Here is my function that returns results in up:

readDataBase() async {
    String data = await DefaultAssetBundle.of(context).loadString("assets/db/tb.json");
    final jsonResult = jsonDecode(data);
    return jsonResult['book'];
}

CodePudding user response:

This should do the trick efficiently;

 List items = [
    {"name": "Imamat", "short_name": "Lev", 'chapters': 27, "name_en": "Leviticus", "type": "old", "order": 3},
    {"name": "Kejadian", "short_name": "Gen", "chapters": 50, "name_en": "Genesis", "type": "old", "order": 1},
    ];
  
  getOrderNo (e)=>e["order"];
  items.sort((a, b) => getOrderNo(a).compareTo(getOrderNo(b)));
  print(items);
  • Related