View Sorted Json Data in a Flutter Table

Issue

[
  {
    "1": {
      "name": "Shahed Emon",
      "win_rate": "98.7%"
    }
  },
  {
    "2": {
      "name": "Mustakim Nahid",
      "win_rate": "88.7%"
    }
  },
  {
    "3": {
      "name": "Imtiaz Rizan",
      "win_rate": "72.3%"
    }
  },
  {
    "4": {
      "name": "Ishtiak Rongon",
      "win_rate": "52.6%"
    }
  }
]

I have this json data. Which i sorted by ‘win_rate’ using this-

final data = json.decode(jsonData);
  data.sort((a, b) =>
      a.values.first["win_rate"].compareTo(b.values.first["win_rate"]));

now I want to build a table in flutter which matches highest ‘win_rate’ with lowest ‘win_rate’ names.
How to approach it?
I tried this but I end up getting errors/no data.

Solution

Just get the reversed item from your data and put it in front of current item:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
      color: Colors.yellow,
      child: Table(
        border: TableBorder(horizontalInside: BorderSide(width: 1)),
        children: _sortedData.map(
          (item) {
            final reverseItem = _sortedData[
                _sortedData.length - _sortedData.indexOf(item) - 1];
            return TableRow(
              children: [
                TableCell(
                  child: Text(item.values.first['name']),
                ),
                TableCell(
                  child: Text(reverseItem.values.first['name']),
                )
              ],
            );
          },
        ).toList(),
      ),
    ),
  );
}

Also you can loop sorted data and create the matched array out of build function.

Answered By – Hamed Hamedi

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *