1
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】ボトムシートを開いたときにキーボードを自動表示する

1
Posted at

前にボトムシートで入力して追加する画面を作りました。
その時に開いたときにキーボードを自動表示したら楽だと思い、実装しました。

1. autofocus でキーボードを自動表示

TextField(
  controller: controller,
  autofocus: true, // ← これだけ
  decoration: InputDecoration(
    labelText: '商品名',
    border: const OutlineInputBorder(),
    errorText: errorText,
  ),
),

autofocus: true を付けると、ボトムシート表示と同時にキーボードが立ち上がります。

2. キーボードに隠れないよう余白を確保

キーボード表示時、入力欄やボタンが隠れないように viewInsets.bottom で余白を足します。

Padding(
  padding: EdgeInsets.fromLTRB(
    16,
    16,
    16,
    MediaQuery.of(context).viewInsets.bottom + 16,
    // ↑ キーボードの高さ分 + 16px
  ),
  child: Column(
    children: [
      TextField(autofocus: true, ...),
      DropdownButtonFormField(...),
      Row(children: [/* ボタン */]),
    ],
  ),
)

3. showModalBottomSheet 側の設定

await showModalBottomSheet<AddItemResult>(
  context: context,
  isScrollControlled: true, // キーボード表示時にシートを押し上げる
  builder: (_) => const AddItemSheet(),
);

isScrollControlled: true がないと、キーボード表示時にシートが正しくリサイズされないことがあります。

動作の流れ

  1. 「追加」ボタン → showModalBottomSheet
  2. AddItemSheet 表示
  3. TextField の autofocus → キーボード表示
  4. viewInsets.bottom → ボタンがキーボードに隠れない

注意点

TextEditingController は dispose() で破棄する

@override
void dispose() {
  controller.dispose();
  super.dispose();
}

まとめ

autofocus: true + viewInsets.bottom + isScrollControlled: true の3点で、ボトムシート表示時にすぐ入力できる UX を実現できました。

1
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
1
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?