LoginSignup
0
0

【Flutter】画面タップでキーボードをしまう方法

Last updated at Posted at 2024-05-14

はじめに

TextFormFieldを実装した時、キーボードを開く処理は特に必要ありません。
ただ、画面のキーボード以外の部分を触った時に、キーボードをしまう処理は意図的に設定しないといけません。

とても簡単なので、真似してみてください。

開発環境

[Flutterバージョン]
3.16.1

[使用端末]
PC: Macbook Air(M1)

[開発ツール]
VSCode

キーボードをしまう処理

対象とするWidgetの親要素に、GestureDetectorを置き、onTapパラメータとbehaviorパラメータに、以下のコードを渡します。

GestureDetector(
    onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
    behavior: HitTestBehavior.opaque,
    child: ~画面要素~
)

コード全体

class Demo extends StatelessWidget {
  const Demo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Demo"),
      ),
      body: GestureDetector(
        // ここを追加 ===
        onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
        behavior: HitTestBehavior.opaque,
        // ============
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Center(
            child: TextFormField(
              decoration: const InputDecoration(hintText: "テキストを入力してください。"),
            ),
          ),
        ),
      ),
    );
  }
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