0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutterでチェックボックス付きリストを作成する方法

0
Posted at

Flutterで買い物リストやTODOアプリを作る場合、チェックボックス付きのリストを実装したい場面は多いと思います。

今回は実際の買い物リストアプリで使用している、チェックボックス付きリストの実装方法を紹介します。
今回は以下を実装します。

  • Checkbox
  • ListTile
  • テキスト横棒
  • タップで状態変更

実装イメージ

Screenshot_20260515_111354.png

チェック済みのアイテムには横棒を表示します。

@override
Widget build(BuildContext context) {
  return Card(
    elevation: 2,
    margin: const EdgeInsets.symmetric(
      horizontal: 12,
      vertical: 6,
    ),
    child: ListTile(
      onTap: onToggle,
      leading: Checkbox(
        value: item.isChecked,
        onChanged: null,
      ),
      title: Text(
        item.name,
        style: itemTextStyle(
          context,
          item.isChecked,
        ),
      ),
      subtitle: Text(
        '${formatDateTime(item.lastUpdatedAt)}',
      ),
    ),
  );
}

ListTile

ListTile はリスト表示用の便利なWidgetです。

ListTile(
  leading: Widget(),
  title: Widget(),
  subtitle: Widget(),
)

この実装では、

  • leading → Checkbox
  • title → 商品名
  • subtitle → 更新日時
    を表示しています。

Checkbox

チェック状態を表示するWidgetです。

Checkbox(
  value: item.isChecked,
  onChanged: null,
)

valueにチェック状態を指定します。

今回はListTile 全体をタップ可能にしたかったため、onChangedはnullにしています。
onToggleはVoidCallbackを設定しています。

テキスト横棒

チェック済みの場合は、テキストに取り消し線を表示しています。```dart
style: itemTextStyle(
context,
item.isChecked,
),

```dart
  TextStyle itemTextStyle(BuildContext context, bool isChecked) {
    final base = Theme.of(context).textTheme.titleMedium!;
    return base.copyWith(
      fontWeight: FontWeight.bold,
      decoration:
      isChecked ? TextDecoration.lineThrough : TextDecoration.none,
      color: isChecked ? Theme.of(context).disabledColor : null,
    );
  }

TextDecoration.lineThrough を指定すると、取り消し線を表示できます。

Flutterでは、簡単にチェック付きリストを実装できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?