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(() { _color = Colors.red; });
43 return KeyEventResult.handled;
44 case LogicalKeyboardKey.keyG:
45 debugPrint('Changing color to green.');
46 setState(() { _color = Colors.green; });
47 return KeyEventResult.handled;
48 case LogicalKeyboardKey.keyB:
49 debugPrint('Changing color to blue.');
50 setState(() { _color = Colors.blue; });
51 return KeyEventResult.handled;
52 }
53 }
54 return KeyEventResult.ignored;
55 }
56
57 @override
58 Widget build(BuildContext context) {
59 final TextTheme textTheme = Theme.of(context).textTheme;
60 return FocusScope(
61 debugLabel: 'Scope',
62 autofocus: true,
63 child: DefaultTextStyle(
64 style: textTheme.headlineMedium!,
65 child: Focus(
66 onKeyEvent: _handleKeyPress,
67 debugLabel: 'Button',
68 child: Builder(
69 builder: (BuildContext context) {
70 final FocusNode focusNode = Focus.of(context);
71 final bool hasFocus = focusNode.hasFocus;
72 return GestureDetector(
73 onTap: () {
74 if (hasFocus) {
75 focusNode.unfocus();
76 } else {
77 focusNode.requestFocus();
78 }
79 },
80 child: Center(
81 child: Container(
82 width: 400,
83 height: 100,
84 alignment: Alignment.center,
85 color: hasFocus ? _color : Colors.white,
86 child: Text(hasFocus ? "I'm in color! Press R,G,B!" : 'Press to focus'),
87 ),
88 ),
89 );
90 },
91 ),
92 ),
93 ),
94 );
95 }
96}
97

Provided by KDAB

Privacy Policy
Learn more about Flutter for embedded and desktop on industrialflutter.com