Last active
March 23, 2025 19:21
-
-
Save prof3ssorSt3v3/5bc77b01868b9842c82a25fdb1aec0c0 to your computer and use it in GitHub Desktop.
Flutter FocusNodes and TextFields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
class FocusTextFieldScreen extends StatefulWidget { | |
@override | |
_FocusTextFieldScreenState createState() => _FocusTextFieldScreenState(); | |
} | |
class _FocusTextFieldScreenState extends State<FocusTextFieldScreen> { | |
FocusNode textField1FocusNode = FocusNode(); | |
FocusNode textField2FocusNode = FocusNode(); | |
FocusNode textField3FocusNode = FocusNode(); | |
late TextEditingController _controller1; | |
late TextEditingController _controller2; | |
late TextEditingController _controller3; | |
String focusedTextField = "None"; | |
@override | |
void initState() { | |
super.initState(); | |
_controller1 = TextEditingController(); | |
_controller2 = TextEditingController(); | |
_controller3 = TextEditingController(); | |
textField1FocusNode.addListener(_onFocusChange); | |
textField2FocusNode.addListener(_onFocusChange); | |
textField3FocusNode.addListener(_onFocusChange); | |
} | |
@override | |
void dispose() { | |
textField1FocusNode.dispose(); | |
textField2FocusNode.dispose(); | |
textField3FocusNode.dispose(); | |
_controller1.dispose(); | |
_controller2.dispose(); | |
_controller3.dispose(); | |
super.dispose(); | |
} | |
void _onFocusChange() { | |
setState(() { | |
if (textField1FocusNode.hasFocus) { | |
focusedTextField = "TextField 1"; | |
} else if (textField2FocusNode.hasFocus) { | |
focusedTextField = "TextField 2"; | |
} else if (textField3FocusNode.hasFocus) { | |
focusedTextField = "TextField 3"; | |
} else { | |
focusedTextField = "None"; | |
} | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Focus Tracking')), | |
body: Padding( | |
padding: const EdgeInsets.all(16.0), | |
child: Column( | |
children: <Widget>[ | |
TextField( | |
focusNode: textField1FocusNode, | |
controller: _controller1, | |
decoration: InputDecoration(labelText: 'TextField 1'), | |
), | |
TextField( | |
focusNode: textField2FocusNode, | |
controller: _controller2, | |
decoration: InputDecoration(labelText: 'TextField 2'), | |
), | |
TextField( | |
focusNode: textField3FocusNode, | |
controller: _controller3, | |
decoration: InputDecoration(labelText: 'TextField 3'), | |
), | |
SizedBox(height: 20), | |
Text('Focused TextField: $focusedTextField'), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment