flutter/dev/manual_tests/lib/focus.dart
Nate Wilson 5ecf10052f
pattern-matching refactor (#154753)
This pull request aims to improve code readability, based on feedback gathered in a recent design doc.

<br>

There are two factors that hugely impact how easy it is to understand a piece of code: **verbosity** and **complexity**.

Reducing **verbosity** is important, because boilerplate makes a project more difficult to navigate. It also has a tendency to make one's eyes gloss over, and subtle typos/bugs become more likely to slip through.

Reducing **complexity** makes the code more accessible to more people. This is especially important for open-source projects like Flutter, where the code is read by those who make contributions, as well as others who read through source code as they debug their own projects.

<hr>

<br>

The following examples show how pattern-matching might affect these two factors:

<details> <summary><h3>Example 1 (GOOD)</h3> [click to expand]</summary>

```dart
if (ancestor case InheritedElement(:final InheritedTheme widget)) {
  themes.add(widget);
}
```

Without using patterns, this might expand to

```dart
if (ancestor is InheritedElement) {
  final InheritedWidget widget = ancestor.widget;
  if (widget is InheritedTheme) {
    themes.add(widget);
  }
}
```

Had `ancestor` been a non-local variable, it would need to be "converted" as well:

```dart
final Element ancestor = this.ancestor;
if (ancestor is InheritedElement) {
  final InheritedWidget inheritedWidget = ancestor.widget;
  if (widget is InheritedTheme) {
    themes.add(theme);
  }
}
```

</details>

<details> <summary><h3>Example 2 (BAD) </h3> [click to expand]</summary>

```dart
if (widget case PreferredSizeWidget(preferredSize: Size(:final double height))) {
  return height;
}
```

Assuming `widget` is a non-local variable, this would expand to:

```dart
final Widget widget = this.widget;
if (widget is PreferredSizeWidget) {
  return widget.preferredSize.height;
}
```

<br>

</details>

In both of the examples above, an `if-case` statement simultaneously verifies that an object meets the specified criteria and performs a variable assignment accordingly.

But there are some differences: Example 2 uses a more deeply-nested pattern than Example 1 but makes fewer useful checks.

**Example 1:**
- checks that `ancestor` is an `InheritedElement`
- checks that the inherited element's `widget` is an `InheritedTheme`

**Example 2:**
- checks that `widget` is a `PreferredSizeWidget`
(every `PreferredSizeWidget` has a `size` field, and every `Size` has a `height` field)

<br>

<hr>

I feel hesitant to try presenting a set of cut-and-dry rules as to which scenarios should/shouldn't use pattern-matching, since there are an abundance of different types of patterns, and an abundance of different places where they might be used.

But hopefully the conversations we've had recently will help us converge toward a common intuition of how pattern-matching can best be utilized for improved readability.

<br><br>

- resolves https://github.com/flutter/flutter/issues/152313
- Design Doc: [flutter.dev/go/dart-patterns](https://flutter.dev/go/dart-patterns)
2024-10-03 18:21:04 +00:00

205 lines
6.2 KiB
Dart

// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MaterialApp(
title: 'Focus Demo',
home: FocusDemo(),
));
}
class DemoButton extends StatefulWidget {
const DemoButton({super.key, required this.name, this.canRequestFocus = true, this.autofocus = false});
final String name;
final bool canRequestFocus;
final bool autofocus;
@override
State<DemoButton> createState() => _DemoButtonState();
}
class _DemoButtonState extends State<DemoButton> {
late final FocusNode focusNode = FocusNode(
debugLabel: widget.name,
canRequestFocus: widget.canRequestFocus,
);
@override
void dispose() {
focusNode.dispose();
super.dispose();
}
@override
void didUpdateWidget(DemoButton oldWidget) {
super.didUpdateWidget(oldWidget);
focusNode.canRequestFocus = widget.canRequestFocus;
}
void _handleOnPressed() {
focusNode.requestFocus();
print('Button ${widget.name} pressed.');
debugDumpFocusTree();
}
@override
Widget build(BuildContext context) {
return TextButton(
focusNode: focusNode,
autofocus: widget.autofocus,
style: ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.focused)) {
return Colors.red.withOpacity(0.25);
}
if (states.contains(MaterialState.hovered)) {
return Colors.blue.withOpacity(0.25);
}
return Colors.transparent;
}),
),
onPressed: () => _handleOnPressed(),
child: Text(widget.name),
);
}
}
class FocusDemo extends StatefulWidget {
const FocusDemo({super.key});
@override
State<FocusDemo> createState() => _FocusDemoState();
}
class _FocusDemoState extends State<FocusDemo> {
FocusNode? outlineFocus;
@override
void initState() {
super.initState();
outlineFocus = FocusNode(debugLabel: 'Demo Focus Node');
}
@override
void dispose() {
outlineFocus?.dispose();
super.dispose();
}
KeyEventResult _handleKeyPress(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent) {
print('Scope got key event: ${event.logicalKey}, $node');
print('Keys down: ${HardwareKeyboard.instance.logicalKeysPressed}');
if (event.logicalKey == LogicalKeyboardKey.tab) {
debugDumpFocusTree();
if (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft)
|| HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight)) {
print('Moving to previous.');
node.previousFocus();
return KeyEventResult.handled;
} else {
print('Moving to next.');
node.nextFocus();
return KeyEventResult.handled;
}
}
final TraversalDirection? direction = switch (event.logicalKey) {
LogicalKeyboardKey.arrowLeft => TraversalDirection.left,
LogicalKeyboardKey.arrowRight => TraversalDirection.right,
LogicalKeyboardKey.arrowUp => TraversalDirection.up,
LogicalKeyboardKey.arrowDown => TraversalDirection.down,
_ => null,
};
if (direction != null) {
node.focusInDirection(direction);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
return FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: FocusScope(
debugLabel: 'Scope',
onKeyEvent: _handleKeyPress,
autofocus: true,
child: DefaultTextStyle(
style: textTheme.headlineMedium!,
child: Scaffold(
appBar: AppBar(
title: const Text('Focus Demo'),
),
floatingActionButton: FloatingActionButton(
child: const Text('+'),
onPressed: () {},
),
body: Center(
child: Builder(builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(
name: 'One',
autofocus: true,
),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Two'),
DemoButton(
name: 'Three',
canRequestFocus: false,
),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Four'),
DemoButton(name: 'Five'),
DemoButton(name: 'Six'),
],
),
OutlinedButton(onPressed: () => print('pressed'), child: const Text('PRESS ME')),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(labelText: 'Enter Text', filled: true),
),
),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Text',
filled: false,
),
),
),
],
);
}),
),
),
),
),
);
}
}