I have two TextFields, I would like that clicking on another widget (Button, Container, Card) won't take away the focus of the TextField that is currently focused. How can I also get information about which text field is currently focused?
Scaffold(
body: Container(
width: 250,
child: Column(children: [
TextField(
focusNode: _focusNode,
autofocus: true,
),
TextField(
focusNode: _secondFocusNode,
),
Focus(
child: OutlinedButton(
onPressed: () {
debugPrint('Has Focus: ${_focusNode.hasFocus}');
debugPrint(
'Has Primary Focus: ${_focusNode.hasPrimaryFocus}');
},
child: Center(child: Text('Click me!'))))
])))
Additionally, when I have focus on one of the TextField, I don't know why, but if I click the button, I get:
- 'Has Focus: false'
- 'Has Primary Focus: false'
CodePudding user response:
You can track the current activeFocuseNode
and use onTap
to select the value on TextFiled
, and recall the FocusNode
again.
final List<FocusNode> _focusNodes = List.generate(2, (index) => FocusNode());
int activeFocuseNode = -1;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: 250,
child: Column(
children: [
TextField(
focusNode: _focusNodes[0],
autofocus: true,
onTap: () {
setState(() {
activeFocuseNode = 0;
});
},
),
TextField(
focusNode: _focusNodes[1],
onTap: () {
setState(() {
activeFocuseNode = 1;
});
},
),
Focus(
child: OutlinedButton(
onPressed: () {
debugPrint('Has Focus: ${_focusNodes[0].hasFocus}');
debugPrint(
'Has Primary Focus: ${_focusNodes[1].hasPrimaryFocus}');
if (activeFocuseNode >= 0) {
FocusScope.of(context)
.requestFocus(_focusNodes[activeFocuseNode]);
}
},
child: const Center(
child: Text('Click me!'),
),
),
)
],
),
),
);
}