LoginSignup
55
30

More than 1 year has passed since last update.

FlutterでTextFieldのフォーカスを正しく外す方法

Last updated at Posted at 2020-09-11

環境

Flutter 1.20.3

方法

return Scaffold(
  body: GestureDetector(
    onTap: () {
      final FocusScopeNode currentScope = FocusScope.of(context);
      if (!currentScope.hasPrimaryFocus && currentScope.hasFocus) {
        FocusManager.instance.primaryFocus!.unfocus();
      }
    },
      child: TextField(),
  ),
);

参考:
https://github.com/flutter/flutter/issues/54277

余談

ググるとstackoverflowとかトップ辺りに出てくる情報だと、大体下記の方法を紹介されています。

return Scaffold(
    body: GestureDetector(
        onTap() {
            FocusScope.of(context).unfocus();
        },
        child: TextField(),
    ),
);

ただ、この方法だとGitHubのissuesにあるように、Drawerを閉じたときに再度TextFieldがフォーカスされキーボードが開いてしまいます。どうやら少し古いバージョンであればこれでも問題なかったようです。

日本語でこのことに関して説明された記事等がなさそうだったので、備忘録も兼ねて書いておきます。

2022/10/03 追記

コードをNNBDに対応したものに変更しました。

55
30
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
55
30