Change focus example to be more canonical (and correct), listening to the focus node for changes. (#35913)
This changes the example for FocusNode to be more correct, listening to the focus node for changes, instead of assuming that it is the only one doing the changing.
diff --git a/packages/flutter/lib/src/widgets/focus_manager.dart b/packages/flutter/lib/src/widgets/focus_manager.dart
index 572e218..5f00e06 100644
--- a/packages/flutter/lib/src/widgets/focus_manager.dart
+++ b/packages/flutter/lib/src/widgets/focus_manager.dart
@@ -236,6 +236,7 @@
///
/// class _ColorfulButtonState extends State<ColorfulButton> {
/// FocusNode _node;
+/// bool _focused = false;
/// FocusAttachment _nodeAttachment;
/// Color _color = Colors.white;
///
@@ -243,9 +244,18 @@
/// void initState() {
/// super.initState();
/// _node = FocusNode(debugLabel: 'Button');
+/// _node.addListener(_handleFocusChange);
/// _nodeAttachment = _node.attach(context, onKey: _handleKeyPress);
/// }
///
+/// void _handleFocusChange() {
+/// if (_node.hasFocus != _focused) {
+/// setState(() {
+/// _focused = _node.hasFocus;
+/// });
+/// }
+/// }
+///
/// bool _handleKeyPress(FocusNode node, RawKeyEvent event) {
/// if (event is RawKeyDownEvent) {
/// print('Focus node ${node.debugLabel} got key event: ${event.logicalKey}');
@@ -274,6 +284,7 @@
///
/// @override
/// void dispose() {
+/// _node.removeListener(_handleFocusChange);
/// // The attachment will automatically be detached in dispose().
/// _node.dispose();
/// super.dispose();
@@ -284,24 +295,20 @@
/// _nodeAttachment.reparent();
/// return GestureDetector(
/// onTap: () {
-/// if (_node.hasFocus) {
-/// setState(() {
+/// if (_focused) {
/// _node.unfocus();
-/// });
/// } else {
-/// setState(() {
-/// _node.requestFocus();
-/// });
+/// _node.requestFocus();
/// }
/// },
/// child: Center(
/// child: Container(
/// width: 400,
/// height: 100,
-/// color: _node.hasFocus ? _color : Colors.white,
+/// color: _focused ? _color : Colors.white,
/// alignment: Alignment.center,
/// child: Text(
-/// _node.hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'),
+/// _focused ? "I'm in color! Press R,G,B!" : 'Press to focus'),
/// ),
/// ),
/// );