1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import 'package:flutter/material.dart';
6import 'package:flutter/services.dart';
7
8/// Flutter code sample for [Focus].
9
10void main() => runApp(const FocusExampleApp());
11
12class FocusExampleApp extends StatelessWidget {
13 const FocusExampleApp({super.key});
14
15 @override
16 Widget build(BuildContext context) {
17 return MaterialApp(
18 home: Scaffold(
19 appBar: AppBar(title: const Text('Focus Sample')),
20 body: const FocusExample(),
21 ),
22 );
23 }
24}
25
26class FocusExample extends StatefulWidget {
27 const FocusExample({super.key});
28
29 @override
30 State<FocusExample> createState() => _FocusExampleState();
31}
32
33class _FocusExampleState extends State<FocusExample> {
34 Color _color = Colors.white;
35
36 KeyEventResult _handleKeyPress(FocusNode node, KeyEvent event) {
37 if (event is KeyDownEvent) {
38 debugPrint('Focus node ${node.debugLabel} got key event: ${event.logicalKey}');
39 switch (event.logicalKey) {
40 case LogicalKeyboardKey.keyR:
41 debugPrint('Changing color to red.');
42 setState(() {
43 _color = Colors.red;
44 });
45 return KeyEventResult.handled;
46 case LogicalKeyboardKey.keyG:
47 debugPrint('Changing color to green.');
48 setState(() {
49 _color = Colors.green;
50 });
51 return KeyEventResult.handled;
52 case LogicalKeyboardKey.keyB:
53 debugPrint('Changing color to blue.');
54 setState(() {
55 _color = Colors.blue;
56 });
57 return KeyEventResult.handled;
58 }
59 }
60 return KeyEventResult.ignored;
61 }
62
63 @override
64 Widget build(BuildContext context) {
65 final TextTheme textTheme = Theme.of(context).textTheme;
66 return FocusScope(
67 debugLabel: 'Scope',
68 autofocus: true,
69 child: DefaultTextStyle(
70 style: textTheme.headlineMedium!,
71 child: Focus(
72 onKeyEvent: _handleKeyPress,
73 debugLabel: 'Button',
74 child: Builder(
75 builder: (BuildContext context) {
76 final FocusNode focusNode = Focus.of(context);
77 final bool hasFocus = focusNode.hasFocus;
78 return GestureDetector(
79 onTap: () {
80 if (hasFocus) {
81 focusNode.unfocus();
82 } else {
83 focusNode.requestFocus();
84 }
85 },
86 child: Center(
87 child: Container(
88 width: 400,
89 height: 100,
90 alignment: Alignment.center,
91 color: hasFocus ? _color : Colors.white,
92 child: Text(hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'),
93 ),
94 ),
95 );
96 },
97 ),
98 ),
99 ),
100 );
101 }
102}
103