19
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FlutterでTextFieldにフォーカスが当たっているかどうか判定する

Posted at

検索などを実装するときに、キーボードにフォーカスが当たった瞬間別の画面を出すみたいな実装をする場合はがあるかと思います。

例えばこんな感じ

mojikyo45_640-2.gif

このときの実装方法について説明します。

FocusNodeを使う

FucusNodeにリスナーをセットし、TextFieldに設定するだけです。


class Search extends StatefulWidget {
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  FocusNode _focus = new FocusNode();
  bool _isFocus = false;

  @override
  void initState() {
    _bloc = SearchBloc();
    super.initState();
    _focus.addListener(_onFocusChange);
  }

  void _onFocusChange() {
    debugPrint("Focus: " + _focus.hasFocus.toString());
    setState(() {
      _isFocus = _focus.hasFocus;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Search",
          style: TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: CustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    height: 40,
                    margin: const EdgeInsets.all(10),
                    child: TextField(
                      focusNode: _focus,  設定する
                      decoration: InputDecoration(
                        hintText: "User name",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: BorderSide(),
                        ),
                      ),
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  onPressed: () {},
                )
              ],
            ),
          ),
          _isFocus
              ? // フォーカスがあたってるときのWidget
              : // フォーカスがあたってないときのWidget,
        ],
      ),
    );
  }

  Widget _newUserList() {
     return Container(
        child: // フォーカスがあたってないときのWidget
     )
  }


以上です。

19
8
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
19
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?