どうも、ちょげ(@chogetarou)です。
DataTableをソートする方法を紹介します。
方法

まず、ソートに必要な変数を指定します。
var _isAscending = true; //降順か昇順か
var _currentSortColumn = 0; //ソート中のカラム
次に、変数をDataTableの引数「sortColumnIndex」と引数「sortAscending」に指定します。
DataTable(
sortColumnIndex: _currentSortColumn, //どのカラムがソート中か
sortAscending: _isAscending, //降順か昇順か
columns: [
・・・・
],
rows: [
・・・・
]
),
最後に、ソートするDataColumnの引数「onSort」にソートする時に呼び出す関数を指定します。
DataColumn(
label: /*項目*/,
onSort: (columnIndex, isAscending) {
//ソート処理
},
),
関数の処理では、ソート中のインデックスの更新、降順か昇順かの更新、ソートなどを行います。
これでDataTableの項目をタップした時にソートすることが出来るようになります。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _isAscending = true;
var _currentSortColumn = 0;
List<Map> _list = List.generate(
15,
(index) => {
'id': index,
'name': 'Product $index',
'price': Random().nextInt(300) + 1,
},
);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SizedBox(
child: DataTable(
sortColumnIndex: _currentSortColumn,
sortAscending: _isAscending,
columns: [
DataColumn(
label: Text('id'),
),
DataColumn(
label: Text('名前'),
),
DataColumn(
label: Text('値段'),
onSort: (columnIndex, isAscending) {
setState(() {
_currentSortColumn = columnIndex;
if (_isAscending == true) {
_isAscending = false;
//高い順
_list.sort(
(a, b) => b['price'].compareTo(a['price']),
);
} else {
_isAscending = true;
//安い順
_list.sort((a, b) => a['price'].compareTo(b['price']));
}
});
},
),
],
rows: _list
.map(
(e) => DataRow(
cells: [
DataCell(
Text('${e['id']}'),
),
DataCell(
Text('${e['name']}'),
),
DataCell(
Text('${e['price']}円'),
),
],
),
)
.toList(),
),
width: double.infinity,
),
),
);
}
}
コメント