Flutter TextFormFieldのフォーカスを外すサンプル

環境
Windows11 pro 64bit
Flutter 3.3.7

構文
TextFormFieldのフォーカスを外すには、FocusNodeを使います。

作成方法
1.FocusNodeの変数を定義し、TextFormFieldの引数「focusNode」に指定します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
TextFormField(
focusNode: _focusNode,
),
TextFormField( focusNode: _focusNode, ),
TextFormField(
focusNode: _focusNode,
),

2.フォーカスを外すボタン処理で、FocusNodeのunfocus()メソッドを呼び出します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
onPressed: () {
_focusNode.unfocus();
},
onPressed: () { _focusNode.unfocus(); },
onPressed: () {
_focusNode.unfocus();
},

unfocusが呼ばれると、TextFormFieldのフォーカスが外されます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
FocusNode _focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
focusNode: _focusNode,
decoration: InputDecoration(
border: OutlineInputBorder(),
),
),
SizedBox(
height: 25,
),
ElevatedButton(
onPressed: () {
_focusNode.unfocus();
},
child: Text('test'),
)
],
),
),
),
);
}
FocusNode _focusNode = FocusNode(); @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Padding( padding: const EdgeInsets.all(10.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormField( focusNode: _focusNode, decoration: InputDecoration( border: OutlineInputBorder(), ), ), SizedBox( height: 25, ), ElevatedButton( onPressed: () { _focusNode.unfocus(); }, child: Text('test'), ) ], ), ), ), ); }
FocusNode _focusNode = FocusNode();

 @override
 Widget build(BuildContext context) {
   return SafeArea(
     child: Scaffold(
       body: Padding(
         padding: const EdgeInsets.all(10.0),
         child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: [
             TextFormField(
               focusNode: _focusNode,
               decoration: InputDecoration(
                 border: OutlineInputBorder(),
               ),
             ),
             SizedBox(
               height: 25,
             ),
             ElevatedButton(
               onPressed: () {
                 _focusNode.unfocus();
               },
               child: Text('test'),
             )
           ],
         ),
       ),
     ),
   );
 }

 

Flutter

Posted by arkgame