どうも、ちょげ(@chogetarou)です。
DataTableでチェックボックスを使う方法を紹介します。
方法

DataTableでチェックボックスを使うには、まず「チェックボックス」がチェック中かどうかを判別するBool値を用意します。
//例
List<Map> _list = List.generate(
14,
(index) => {
'check': false, //チェック中かどうか
'name': 'Product $index',
'price': Random().nextInt(300) + 1,
},
);
そして、チェックボックスを表示したいDataRowの引数「selected」にチェック中かどうかのBool値、引数「onSelectedChanged」にチェック変更時の処理を指定します。
DataRow(
selected: /*チェック中かどうかのBool値*/,
onSelectChanged: (bool? selected) {
//チェックが変更された時の処理
},
cells: [
・・・
],
),
これでDataTableでチェックボックスを使うことが出来るようになります。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Map> _list = List.generate(
14,
(index) => {
'check': false,
'name': 'Product $index',
'price': Random().nextInt(300) + 1,
},
);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
child: DataTable(
columns: [
DataColumn(
label: Text('名前'),
),
DataColumn(
label: Text('値段'),
),
],
rows: _list
.map(
(e) => DataRow(
selected: e['check'],
onSelectChanged: (bool? selected) {
setState(() {
e['check'] = selected;
});
},
cells: [
DataCell(
Text('${e['name']}'),
),
DataCell(
Text('${e['price']}円'),
),
],
),
)
.toList(),
),
width: double.infinity,
),
),
),
);
}
}
コメント