custom_a11y_traversal.dart 10.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7
// 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/semantics.dart';

8 9
/// This example shows a set of widgets for changing data fields arranged in a
/// column of rows but, in accessibility mode, are traversed in a custom order.
10
///
11 12
/// This demonstrates how Flutter's accessibility system describes custom
/// traversal orders using sort keys.
13
///
14 15 16 17
/// The example app here has three fields that have a title and up/down spinner
/// buttons above and below. The traversal order should allow the user to focus
/// on each title, the input field next, the up spinner next, and the down
/// spinner last before moving to the next input title.
18
///
19 20
/// Users that do not use a screen reader (e.g. TalkBack on Android and
/// VoiceOver on iOS) will just see a regular app with controls.
21
///
22 23 24 25
/// The example's [RowColumnTraversal] widget sets up two [Semantics] objects
/// that wrap the given [Widget] child, providing the traversal order they
/// should have in the "row" direction, and then the traversal order they should
/// have in the "column" direction.
26 27
///
/// Since widgets are globally sorted by their sort key, the order does not have
28 29
/// to conform to the widget hierarchy. Indeed, in this example, we traverse
/// vertically first, but the widget hierarchy is a column of rows.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
///
/// See also:
///
///  * [Semantics] for an object that annotates widgets with accessibility semantics
///    (including traversal order).
///  * [SemanticSortKey] for the base class of all semantic sort keys.
///  * [OrdinalSortKey] for a concrete sort key that sorts based on the given ordinal.
class RowColumnTraversal extends StatelessWidget {
  const RowColumnTraversal({this.rowOrder, this.columnOrder, this.child});

  final int rowOrder;
  final int columnOrder;
  final Widget child;

  /// Builds a widget hierarchy that wraps [child].
  ///
46
  /// This function expresses the sort keys as a hierarchy.
47 48
  @override
  Widget build(BuildContext context) {
49 50 51 52
    return Semantics(
      sortKey: OrdinalSortKey(columnOrder.toDouble()),
      child: Semantics(
        sortKey: OrdinalSortKey(rowOrder.toDouble()),
53 54 55 56 57 58 59 60 61 62 63
        child: child,
      ),
    );
  }
}

// --------------- Component widgets ---------------------

/// A Button class that wraps an [IconButton] with a [RowColumnTraversal] to
/// set its traversal order.
class SpinnerButton extends StatelessWidget {
64 65 66 67 68 69 70 71 72
  const SpinnerButton({
    Key key,
    this.onPressed,
    this.icon,
    this.rowOrder,
    this.columnOrder,
    this.field,
    this.increment,
  }) : super(key: key);
73 74 75 76 77 78 79 80 81 82 83 84

  final VoidCallback onPressed;
  final IconData icon;
  final int rowOrder;
  final int columnOrder;
  final Field field;
  final bool increment;

  @override
  Widget build(BuildContext context) {
    final String label = '${increment ? 'Increment' : 'Decrement'} ${_fieldToName(field)}';

85
    return RowColumnTraversal(
86 87
      rowOrder: rowOrder,
      columnOrder: columnOrder,
88 89 90
      child: Center(
        child: IconButton(
          icon: Icon(icon),
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
          onPressed: onPressed,
          tooltip: label,
        ),
      ),
    );
  }
}

/// A text entry field that wraps a [TextField] with a [RowColumnTraversal] to
/// set its traversal order.
class FieldWidget extends StatelessWidget {
  const FieldWidget({
    Key key,
    this.rowOrder,
    this.columnOrder,
    this.onIncrease,
    this.onDecrease,
    this.value,
    this.field,
  }) : super(key: key);

  final int rowOrder;
  final int columnOrder;
  final VoidCallback onDecrease;
  final VoidCallback onIncrease;
  final int value;
  final Field field;

  @override
  Widget build(BuildContext context) {
    final String stringValue = '${_fieldToName(field)} $value';
    final String increasedValue = '${_fieldToName(field)} ${value + 1}';
    final String decreasedValue = '${_fieldToName(field)} ${value - 1}';

125
    return RowColumnTraversal(
126 127
      rowOrder: rowOrder,
      columnOrder: columnOrder,
128 129
      child: Center(
        child: Semantics(
130 131 132 133 134
          onDecrease: onDecrease,
          onIncrease: onIncrease,
          value: stringValue,
          increasedValue: increasedValue,
          decreasedValue: decreasedValue,
135
          child: ExcludeSemantics(child: Text(value.toString())),
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        ),
      ),
    );
  }
}

// --------------- Field manipulation functions ---------------------

/// An enum that describes which column we're referring to.
enum Field { DOGS, CATS, FISH }

String _fieldToName(Field field) {
  switch (field) {
    case Field.DOGS:
      return 'Dogs';
    case Field.CATS:
      return 'Cats';
    case Field.FISH:
      return 'Fish';
  }
  return null;
}

// --------------- Main app ---------------------

/// The top-level example widget that serves as the body of the app.
class CustomTraversalExample extends StatefulWidget {
  @override
164
  CustomTraversalExampleState createState() => CustomTraversalExampleState();
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
}

/// The state object for the top level example widget.
class CustomTraversalExampleState extends State<CustomTraversalExample> {
  /// The fields that we are manipulating. List indices correspond to
  /// the entries in the [Field] enum.
  List<int> fields = <int>[0, 0, 0];

  void _addToField(Field field, int delta) {
    setState(() {
      fields[field.index] += delta;
    });
  }

  Widget _makeFieldHeader(int rowOrder, int columnOrder, Field field) {
180
    return RowColumnTraversal(
181 182
      rowOrder: rowOrder,
      columnOrder: columnOrder,
183
      child: Text(_fieldToName(field)),
184 185 186
    );
  }

187
  Widget _makeSpinnerButton(int rowOrder, int columnOrder, Field field, {bool increment = true}) {
188
    return SpinnerButton(
189 190 191 192 193 194 195 196 197 198
      rowOrder: rowOrder,
      columnOrder: columnOrder,
      icon: increment ? Icons.arrow_upward : Icons.arrow_downward,
      onPressed: () => _addToField(field, increment ? 1 : -1),
      field: field,
      increment: increment,
    );
  }

  Widget _makeEntryField(int rowOrder, int columnOrder, Field field) {
199
    return FieldWidget(
200 201 202 203 204 205 206 207 208 209 210
      rowOrder: rowOrder,
      columnOrder: columnOrder,
      onIncrease: () => _addToField(field, 1),
      onDecrease: () => _addToField(field, -1),
      value: fields[field.index],
      field: field,
    );
  }

  @override
  Widget build(BuildContext context) {
211 212 213
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
214 215
          title: const Text('Pet Inventory'),
        ),
216
        body: Builder(
217
          builder: (BuildContext context) {
218
            return DefaultTextStyle(
219
              style: DefaultTextStyle.of(context).style.copyWith(fontSize: 21.0),
220
              child: Column(
221 222 223
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
224
                  Semantics(
225 226 227 228 229 230 231 232 233 234
                    // Since this is the only sort key that the text has, it
                    // will be compared with the 'column' OrdinalSortKeys of all the
                    // fields, because the column sort keys are first in the other fields.
                    //
                    // An ordinal of "0.0" means that it will be traversed before column 1.
                    sortKey: const OrdinalSortKey(0.0),
                    child: const Text(
                      'How many pets do you own?',
                    ),
                  ),
235
                  const Padding(padding: EdgeInsets.symmetric(vertical: 10.0)),
236
                  Row(
237 238 239 240 241 242 243
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      _makeFieldHeader(1, 0, Field.DOGS),
                      _makeFieldHeader(1, 1, Field.CATS),
                      _makeFieldHeader(1, 2, Field.FISH),
                    ],
                  ),
244
                  Row(
245 246 247 248 249 250 251
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      _makeSpinnerButton(3, 0, Field.DOGS, increment: true),
                      _makeSpinnerButton(3, 1, Field.CATS, increment: true),
                      _makeSpinnerButton(3, 2, Field.FISH, increment: true),
                    ],
                  ),
252
                  Row(
253 254 255 256 257 258 259
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      _makeEntryField(2, 0, Field.DOGS),
                      _makeEntryField(2, 1, Field.CATS),
                      _makeEntryField(2, 2, Field.FISH),
                    ],
                  ),
260
                  Row(
261 262 263 264 265 266 267
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      _makeSpinnerButton(4, 0, Field.DOGS, increment: false),
                      _makeSpinnerButton(4, 1, Field.CATS, increment: false),
                      _makeSpinnerButton(4, 2, Field.FISH, increment: false),
                    ],
                  ),
268
                  const Padding(padding: EdgeInsets.symmetric(vertical: 10.0)),
269
                  Semantics(
270 271 272 273 274 275
                    // Since this is the only sort key that the reset button has, it
                    // will be compared with the 'column' OrdinalSortKeys of all the
                    // fields, because the column sort keys are first in the other fields.
                    //
                    // an ordinal of "5.0" means that it will be traversed after column 4.
                    sortKey: const OrdinalSortKey(5.0),
276
                    child: MaterialButton(
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
                      child: const Text('RESET'),
                      textTheme: ButtonTextTheme.normal,
                      textColor: Colors.blue,
                      onPressed: () {
                        setState(() {
                          fields = <int>[0, 0, 0];
                        });
                      },
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}

void main() {
298
  runApp(CustomTraversalExample());
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
}

/*
Sample Catalog

Title: CustomTraversalExample

Summary: An app that demonstrates a custom semantics traversal order.

Description:
This app presents a value selection interface where the fields can be
incremented or decremented using spinner arrows. In accessibility mode, the
widgets are traversed in a custom order from one column to the next, starting
with the column title, moving to the input field, then to the "up" increment
button, and lastly to the "down" decrement button.

When not in accessibility mode, the app works as one would expect.

Classes: Semantics

Sample: CustomTraversalExample
*/