-
[Flutter] FocusNode 활용Flutter 2023. 10. 30. 15:52
TextField가 여러개 있다면, 원하는 Field에 Focus를 줄 수 있게하는 위젯이다.
보통 키보드의 엔터키를 누르거나, 다음 버튼을 터치했을 때 Cursor가 자동으로 넘어가게 할 때 유용하다.
final FocusNode _focusNode = FocusNode();
이렇게 선언 후 controller처럼 Textfield 하나 당 focusnode 하나를 할당해주면 된다.
TextFormField( autovalidateMode: AutovalidateMode.always, autofocus: true, controller: _textEditingController, focusNode: _focusNode, decoration: InputDecoration( label: Text( 'Enter the text here', style: TextStyle( color: Colors.grey[400], ), ), border: OutlineInputBorder(), focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: PRIMARY_COLOR, ), ), ), cursorColor: PRIMARY_COLOR, cursorWidth: 1, onSaved: (val) { setState(() { atCmd = val as String; }); }, onFieldSubmitted: (val) { // Enter 입력 후 sendText()가 실행되게할 수 있다. FocusScope.of(context).requestFocus(_focusNode); sendText(); _textEditingController.text = ''; }, ),
이런식으로 활용하면
autofocus: true 를 통해 자동으로 포커스를 가진 후,
Enter 입력 시 FocusScope.of(context).requestFocus() 를 통해 포커스를 전달하여 sendText()가 실행되게 활용할 수 있다.
'Flutter' 카테고리의 다른 글
[Dart] Dart에서의 static, const와의 차이점? (0) 2023.11.01 [Dart] "toString"과 "as String" 차이? (0) 2023.10.31 Flutter 생명 주기 (0) 2023.10.23 [Flutter] Text 위젯의 overflow 속성 - 글자 수가 길어 넘어갔을 때 (0) 2023.10.19 [Flutter] IntrinsicHeight 한줄 정리 (0) 2023.10.19