Skip to content

Commit 3b945da

Browse files
authored
Change focus example to be more canonical (and correct), listening to the focus node for changes. (flutter#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.
1 parent 67ee3e1 commit 3b945da

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

packages/flutter/lib/src/widgets/focus_manager.dart

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -236,16 +236,26 @@ class FocusAttachment {
236236
///
237237
/// class _ColorfulButtonState extends State<ColorfulButton> {
238238
/// FocusNode _node;
239+
/// bool _focused = false;
239240
/// FocusAttachment _nodeAttachment;
240241
/// Color _color = Colors.white;
241242
///
242243
/// @override
243244
/// void initState() {
244245
/// super.initState();
245246
/// _node = FocusNode(debugLabel: 'Button');
247+
/// _node.addListener(_handleFocusChange);
246248
/// _nodeAttachment = _node.attach(context, onKey: _handleKeyPress);
247249
/// }
248250
///
251+
/// void _handleFocusChange() {
252+
/// if (_node.hasFocus != _focused) {
253+
/// setState(() {
254+
/// _focused = _node.hasFocus;
255+
/// });
256+
/// }
257+
/// }
258+
///
249259
/// bool _handleKeyPress(FocusNode node, RawKeyEvent event) {
250260
/// if (event is RawKeyDownEvent) {
251261
/// print('Focus node ${node.debugLabel} got key event: ${event.logicalKey}');
@@ -274,6 +284,7 @@ class FocusAttachment {
274284
///
275285
/// @override
276286
/// void dispose() {
287+
/// _node.removeListener(_handleFocusChange);
277288
/// // The attachment will automatically be detached in dispose().
278289
/// _node.dispose();
279290
/// super.dispose();
@@ -284,24 +295,20 @@ class FocusAttachment {
284295
/// _nodeAttachment.reparent();
285296
/// return GestureDetector(
286297
/// onTap: () {
287-
/// if (_node.hasFocus) {
288-
/// setState(() {
298+
/// if (_focused) {
289299
/// _node.unfocus();
290-
/// });
291300
/// } else {
292-
/// setState(() {
293-
/// _node.requestFocus();
294-
/// });
301+
/// _node.requestFocus();
295302
/// }
296303
/// },
297304
/// child: Center(
298305
/// child: Container(
299306
/// width: 400,
300307
/// height: 100,
301-
/// color: _node.hasFocus ? _color : Colors.white,
308+
/// color: _focused ? _color : Colors.white,
302309
/// alignment: Alignment.center,
303310
/// child: Text(
304-
/// _node.hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'),
311+
/// _focused ? "I'm in color! Press R,G,B!" : 'Press to focus'),
305312
/// ),
306313
/// ),
307314
/// );

0 commit comments

Comments
 (0)