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

ドロップダウンで簡単に選択するUIを実装してみます。
今回はサンプルとして、カテゴリーを選択出来るドロップダウンを実装します。

1. enum でカテゴリを定義

// models/category.dart
enum Category {
  food,
  daily,
}
extension CategoryExtension on Category {
  String get label {
    switch (this) {
      case Category.food:
        return '食品';
      case Category.daily:
        return '日用品';
    }
  }
}

表示名(食品)と保存値(food)を分けて管理できます。

2. ドロップダウン UI

class _AddItemSheetState extends State<AddItemSheet> {
  Category selectedCategory = Category.food; // 初期値

  @override
  Widget build(BuildContext context) {
    return DropdownButtonFormField<Category>(
      initialValue: selectedCategory,
      items: Category.values.map((category) {
        return DropdownMenuItem(
          value: category,
          child: Text(category.label), // '食品' / '日用品'
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          selectedCategory = value!;
        });
      },
      decoration: const InputDecoration(
        labelText: 'カテゴリ',
        border: OutlineInputBorder(),
      ),
    );
  }
}

ドロップダウン表示は簡単なので、参考にしてみてください。

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?