stepper.dart 19.7 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/foundation.dart';
6 7 8 9 10 11 12 13 14
import 'package:flutter/widgets.dart';

import 'button.dart';
import 'colors.dart';
import 'debug.dart';
import 'flat_button.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
15
import 'material_localizations.dart';
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import 'theme.dart';
import 'typography.dart';

// TODO(dragostis): Missing functionality:
//   * mobile horizontal mode with adding/removing steps
//   * alternative labeling
//   * stepper feedback in the case of high-latency interactions

/// The state of a [Step] which is used to control the style of the circle and
/// text.
///
/// See also:
///
///  * [Step]
enum StepState {
  /// A step that displays its index in its circle.
  indexed,
33

34 35
  /// A step that displays a pencil icon in its circle.
  editing,
36

37 38
  /// A step that displays a tick icon in its circle.
  complete,
39

40 41
  /// A step that is disabled and does not to react to taps.
  disabled,
42

43 44
  /// A step that is currently having an error. e.g. the use has submitted wrong
  /// input.
45
  error,
46 47 48 49 50 51
}

/// Defines the [Stepper]'s main axis.
enum StepperType {
  /// A vertical layout of the steps with their content in-between the titles.
  vertical,
52

53
  /// A horizontal layout of the steps with their content below the titles.
54
  horizontal,
55 56 57 58
}

const TextStyle _kStepStyle = const TextStyle(
  fontSize: 12.0,
59
  color: Colors.white,
60
);
61 62
final Color _kErrorLight = Colors.red;
final Color _kErrorDark = Colors.red.shade400;
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
const Color _kCircleActiveLight = Colors.white;
const Color _kCircleActiveDark = Colors.black87;
const Color _kDisabledLight = Colors.black38;
const Color _kDisabledDark = Colors.white30;
const double _kStepSize = 24.0;
const double _kTriangleHeight = _kStepSize * 0.866025; // Traingle height. sqrt(3.0) / 2.0

/// A material step used in [Stepper]. The step can have a title and subtitle,
/// an icon within its circle, some content and a state that governs its
/// styling.
///
/// See also:
///
///  * [Stepper]
///  * <https://material.google.com/components/steppers.html>
78
@immutable
79 80 81 82
class Step {
  /// Creates a step for a [Stepper].
  ///
  /// The [title], [content], and [state] arguments must not be null.
83
  const Step({
84 85 86 87
    @required this.title,
    this.subtitle,
    @required this.content,
    this.state: StepState.indexed,
88
    this.isActive: false,
89 90 91
  }) : assert(title != null),
       assert(content != null),
       assert(state != null);
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 125 126 127 128 129 130 131 132 133 134 135 136 137

  /// The title of the step that typically describes it.
  final Widget title;

  /// The subtitle of the step that appears below the title and has a smaller
  /// font size. It typically gives more details that complement the title.
  ///
  /// If null, the subtitle is not shown.
  final Widget subtitle;

  /// The content of the step that appears below the [title] and [subtitle].
  ///
  /// Below the content, every step has a 'continue' and 'cancel' button.
  final Widget content;

  /// The state of the step which determines the styling of its componenents
  /// and whether steps are interactive.
  final StepState state;

  /// Whether or not the step is active. The flag only influences styling.
  final bool isActive;
}

/// A material stepper widget that displays progress through a sequence of
/// steps. Steppers are particularly useful in the case of forms where one step
/// requires the completion of another one, or where multiple steps need to be
/// completed in order to submit the whole form.
///
/// The widget is a flexible wrapper. A parent class should pass [currentStep]
/// to this widget based on some logic triggered by the three callbacks that it
/// provides.
///
/// See also:
///
///  * [Step]
///  * <https://material.google.com/components/steppers.html>
class Stepper extends StatefulWidget {
  /// Creates a stepper from a list of steps.
  ///
  /// This widget is not meant to be rebuilt with a different list of steps
  /// unless a key is provided in order to distinguish the old stepper from the
  /// new one.
  ///
  /// The [steps], [type], and [currentStep] arguments must not be null.
  Stepper({
    Key key,
138
    @required this.steps,
139 140 141 142
    this.type: StepperType.vertical,
    this.currentStep: 0,
    this.onStepTapped,
    this.onStepContinue,
143
    this.onStepCancel,
144 145 146 147 148
  }) : assert(steps != null),
       assert(type != null),
       assert(currentStep != null),
       assert(0 <= currentStep && currentStep < steps.length),
       super(key: key);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

  /// The steps of the stepper whose titles, subtitles, icons always get shown.
  ///
  /// The length of [steps] must not change.
  final List<Step> steps;

  /// The type of stepper that determines the layout. In the case of
  /// [StepperType.horizontal], the content of the current step is displayed
  /// underneath as opposed to the [StepperType.vertical] case where it is
  /// displayed in-between.
  final StepperType type;

  /// The index into [steps] of the current step whose content is displayed.
  final int currentStep;

  /// The callback called when a step is tapped, with its index passed as
  /// an argument.
  final ValueChanged<int> onStepTapped;

  /// The callback called when the 'continue' button is tapped.
  ///
  /// If null, the 'continue' button will be disabled.
  final VoidCallback onStepContinue;

  /// The callback called when the 'cancel' button is tapped.
  ///
  /// If null, the 'cancel' button will be disabled.
  final VoidCallback onStepCancel;

  @override
  _StepperState createState() => new _StepperState();
}

182
class _StepperState extends State<Stepper> with TickerProviderStateMixin {
183
  List<GlobalKey> _keys;
184
  final Map<int, StepState> _oldStates = <int, StepState>{};
185 186 187 188 189

  @override
  void initState() {
    super.initState();
    _keys = new List<GlobalKey>.generate(
190
      widget.steps.length,
191
      (int i) => new GlobalKey(),
192 193
    );

194 195
    for (int i = 0; i < widget.steps.length; i += 1)
      _oldStates[i] = widget.steps[i].state;
196 197 198
  }

  @override
199 200 201
  void didUpdateWidget(Stepper oldWidget) {
    super.didUpdateWidget(oldWidget);
    assert(widget.steps.length == oldWidget.steps.length);
202

203 204
    for (int i = 0; i < oldWidget.steps.length; i += 1)
      _oldStates[i] = oldWidget.steps[i].state;
205 206 207 208 209 210 211
  }

  bool _isFirst(int index) {
    return index == 0;
  }

  bool _isLast(int index) {
212
    return widget.steps.length - 1 == index;
213 214 215
  }

  bool _isCurrent(int index) {
216
    return widget.currentStep == index;
217 218 219 220 221 222 223 224 225 226
  }

  bool _isDark() {
    return Theme.of(context).brightness == Brightness.dark;
  }

  Widget _buildLine(bool visible) {
    return new Container(
      width: visible ? 1.0 : 0.0,
      height: 16.0,
227
      color: Colors.grey.shade400,
228 229 230 231
    );
  }

  Widget _buildCircleChild(int index, bool oldState) {
232 233
    final StepState state = oldState ? _oldStates[index] : widget.steps[index].state;
    final bool isDarkActive = _isDark() && widget.steps[index].isActive;
234 235 236 237 238 239
    assert(state != null);
    switch (state) {
      case StepState.indexed:
      case StepState.disabled:
        return new Text(
          '${index + 1}',
240
          style: isDarkActive ? _kStepStyle.copyWith(color: Colors.black87) : _kStepStyle,
241 242 243 244
        );
      case StepState.editing:
        return new Icon(
          Icons.edit,
245
          color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
246 247 248 249
        );
      case StepState.complete:
        return new Icon(
          Icons.check,
250
          color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
251 252
        );
      case StepState.error:
253
        return const Text('!', style: _kStepStyle);
254 255 256 257 258 259 260
    }
    return null;
  }

  Color _circleColor(int index) {
    final ThemeData themeData = Theme.of(context);
    if (!_isDark()) {
261
      return widget.steps[index].isActive ? themeData.primaryColor : Colors.black38;
262
    } else {
263
      return widget.steps[index].isActive ? themeData.accentColor : themeData.backgroundColor;
264 265 266 267 268 269 270 271 272 273 274 275
    }
  }

  Widget _buildCircle(int index, bool oldState) {
    return new Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      width: _kStepSize,
      height: _kStepSize,
      child: new AnimatedContainer(
        curve: Curves.fastOutSlowIn,
        duration: kThemeAnimationDuration,
        decoration: new BoxDecoration(
276
          color: _circleColor(index),
277
          shape: BoxShape.circle,
278 279
        ),
        child: new Center(
280
          child: _buildCircleChild(index, oldState && widget.steps[index].state == StepState.error),
281 282
        ),
      ),
283 284 285 286 287 288 289 290 291 292 293 294 295 296
    );
  }

  Widget _buildTriangle(int index, bool oldState) {
    return new Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      width: _kStepSize,
      height: _kStepSize,
      child: new Center(
        child: new SizedBox(
          width: _kStepSize,
          height: _kTriangleHeight, // Height of 24dp-long-sided equilateral triangle.
          child: new CustomPaint(
            painter: new _TrianglePainter(
297
              color: _isDark() ? _kErrorDark : _kErrorLight,
298 299
            ),
            child: new Align(
300
              alignment: const Alignment(0.0, 0.8), // 0.8 looks better than the geometrical 0.33.
301
              child: _buildCircleChild(index, oldState && widget.steps[index].state != StepState.error),
302 303 304 305
            ),
          ),
        ),
      ),
306 307 308 309
    );
  }

  Widget _buildIcon(int index) {
310
    if (widget.steps[index].state != _oldStates[index]) {
311 312 313
      return new AnimatedCrossFade(
        firstChild: _buildCircle(index, true),
        secondChild: _buildTriangle(index, true),
314 315
        firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
        secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
316
        sizeCurve: Curves.fastOutSlowIn,
317
        crossFadeState: widget.steps[index].state == StepState.error ? CrossFadeState.showSecond : CrossFadeState.showFirst,
318 319 320
        duration: kThemeAnimationDuration,
      );
    } else {
321
      if (widget.steps[index].state != StepState.error)
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        return _buildCircle(index, false);
      else
        return _buildTriangle(index, false);
    }
  }

  Widget _buildVerticalControls() {
    Color cancelColor;

    switch (Theme.of(context).brightness) {
      case Brightness.light:
        cancelColor = Colors.black54;
        break;
      case Brightness.dark:
        cancelColor = Colors.white70;
        break;
    }

    assert(cancelColor != null);

    final ThemeData themeData = Theme.of(context);
343
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
344 345 346 347 348 349 350 351

    return new Container(
      margin: const EdgeInsets.only(top: 16.0),
      child: new ConstrainedBox(
        constraints: const BoxConstraints.tightFor(height: 48.0),
        child: new Row(
          children: <Widget>[
            new FlatButton(
352
              onPressed: widget.onStepContinue,
353 354 355
              color: _isDark() ? themeData.backgroundColor : themeData.primaryColor,
              textColor: Colors.white,
              textTheme: ButtonTextTheme.normal,
356
              child: new Text(localizations.continueButtonLabel),
357 358
            ),
            new Container(
359
              margin: const EdgeInsetsDirectional.only(start: 8.0),
360
              child: new FlatButton(
361
                onPressed: widget.onStepCancel,
362 363
                textColor: cancelColor,
                textTheme: ButtonTextTheme.normal,
364
                child: new Text(localizations.cancelButtonLabel),
365 366 367 368 369
              ),
            ),
          ],
        ),
      ),
370 371 372 373 374 375 376
    );
  }

  TextStyle _titleStyle(int index) {
    final ThemeData themeData = Theme.of(context);
    final TextTheme textTheme = themeData.textTheme;

377 378
    assert(widget.steps[index].state != null);
    switch (widget.steps[index].state) {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
      case StepState.indexed:
      case StepState.editing:
      case StepState.complete:
        return textTheme.body2;
      case StepState.disabled:
        return textTheme.body2.copyWith(
          color: _isDark() ? _kDisabledDark : _kDisabledLight
        );
      case StepState.error:
        return textTheme.body2.copyWith(
          color: _isDark() ? _kErrorDark : _kErrorLight
        );
    }
    return null;
  }

  TextStyle _subtitleStyle(int index) {
    final ThemeData themeData = Theme.of(context);
    final TextTheme textTheme = themeData.textTheme;

399 400
    assert(widget.steps[index].state != null);
    switch (widget.steps[index].state) {
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
      case StepState.indexed:
      case StepState.editing:
      case StepState.complete:
        return textTheme.caption;
      case StepState.disabled:
        return textTheme.caption.copyWith(
          color: _isDark() ? _kDisabledDark : _kDisabledLight
        );
      case StepState.error:
        return textTheme.caption.copyWith(
          color: _isDark() ? _kErrorDark : _kErrorLight
        );
    }
    return null;
  }

  Widget _buildHeaderText(int index) {
    final List<Widget> children = <Widget>[
      new AnimatedDefaultTextStyle(
        style: _titleStyle(index),
        duration: kThemeAnimationDuration,
        curve: Curves.fastOutSlowIn,
423
        child: widget.steps[index].title,
424
      ),
425 426
    ];

427
    if (widget.steps[index].subtitle != null)
428 429 430 431 432 433 434
      children.add(
        new Container(
          margin: const EdgeInsets.only(top: 2.0),
          child: new AnimatedDefaultTextStyle(
            style: _subtitleStyle(index),
            duration: kThemeAnimationDuration,
            curve: Curves.fastOutSlowIn,
435
            child: widget.steps[index].subtitle,
436 437
          ),
        ),
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
      );

    return new Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: children
    );
  }

  Widget _buildVerticalHeader(int index) {
    return new Container(
      margin: const EdgeInsets.symmetric(horizontal: 24.0),
      child: new Row(
        children: <Widget>[
          new Column(
            children: <Widget>[
              // Line parts are always added in order for the ink splash to
              // flood the tips of the connector lines.
              _buildLine(!_isFirst(index)),
              _buildIcon(index),
              _buildLine(!_isLast(index)),
            ]
          ),
          new Container(
462
            margin: const EdgeInsetsDirectional.only(start: 12.0),
463 464 465 466 467 468 469 470 471 472
            child: _buildHeaderText(index)
          )
        ]
      )
    );
  }

  Widget _buildVerticalBody(int index) {
    return new Stack(
      children: <Widget>[
473 474
        new PositionedDirectional(
          start: 24.0,
475 476 477 478 479 480 481 482
          top: 0.0,
          bottom: 0.0,
          child: new SizedBox(
            width: 24.0,
            child: new Center(
              child: new SizedBox(
                width: _isLast(index) ? 0.0 : 1.0,
                child: new Container(
483
                  color: Colors.grey.shade400,
484 485 486 487
                ),
              ),
            ),
          ),
488 489 490 491
        ),
        new AnimatedCrossFade(
          firstChild: new Container(height: 0.0),
          secondChild: new Container(
492 493 494
            margin: const EdgeInsetsDirectional.only(
              start: 60.0,
              end: 24.0,
495
              bottom: 24.0,
496 497 498
            ),
            child: new Column(
              children: <Widget>[
499
                widget.steps[index].content,
500 501 502
                _buildVerticalControls(),
              ],
            ),
503
          ),
504 505
          firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
          secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
506 507 508
          sizeCurve: Curves.fastOutSlowIn,
          crossFadeState: _isCurrent(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst,
          duration: kThemeAnimationDuration,
509 510
        ),
      ],
511 512 513 514
    );
  }

  Widget _buildVertical() {
515
    final List<Widget> children = <Widget>[];
516

517
    for (int i = 0; i < widget.steps.length; i += 1) {
518 519 520 521 522
      children.add(
        new Column(
          key: _keys[i],
          children: <Widget>[
            new InkWell(
523
              onTap: widget.steps[i].state != StepState.disabled ? () {
524 525
                // In the vertical case we need to scroll to the newly tapped
                // step.
Adam Barth's avatar
Adam Barth committed
526
                Scrollable.ensureVisible(
527 528
                  _keys[i].currentContext,
                  curve: Curves.fastOutSlowIn,
529
                  duration: kThemeAnimationDuration,
530 531
                );

532 533
                if (widget.onStepTapped != null)
                  widget.onStepTapped(i);
534 535 536 537 538 539 540 541 542
              } : null,
              child: _buildVerticalHeader(i)
            ),
            _buildVerticalBody(i)
          ]
        )
      );
    }

543
    return new ListView(
544 545
      shrinkWrap: true,
      children: children,
546 547 548 549 550 551
    );
  }

  Widget _buildHorizontal() {
    final List<Widget> children = <Widget>[];

552
    for (int i = 0; i < widget.steps.length; i += 1) {
553 554
      children.add(
        new InkResponse(
555 556 557
          onTap: widget.steps[i].state != StepState.disabled ? () {
            if (widget.onStepTapped != null)
              widget.onStepTapped(i);
558 559 560 561 562 563
          } : null,
          child: new Row(
            children: <Widget>[
              new Container(
                height: 72.0,
                child: new Center(
564 565
                  child: _buildIcon(i),
                ),
566 567
              ),
              new Container(
568
                margin: const EdgeInsetsDirectional.only(start: 12.0),
569 570 571 572 573
                child: _buildHeaderText(i),
              ),
            ],
          ),
        ),
574 575
      );

576
      if (!_isLast(i)) {
577
        children.add(
578
          new Expanded(
579 580 581
            child: new Container(
              margin: const EdgeInsets.symmetric(horizontal: 8.0),
              height: 1.0,
582
              color: Colors.grey.shade400,
583 584
            ),
          ),
585
        );
586
      }
587 588 589 590 591
    }

    return new Column(
      children: <Widget>[
        new Material(
592
          elevation: 2.0,
593 594 595
          child: new Container(
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: new Row(
596 597 598
              children: children,
            ),
          ),
599
        ),
600
        new Expanded(
601 602 603 604 605 606 607
          child: new ListView(
            padding: const EdgeInsets.all(24.0),
            children: <Widget>[
              new AnimatedSize(
                curve: Curves.fastOutSlowIn,
                duration: kThemeAnimationDuration,
                vsync: this,
608
                child: widget.steps[widget.currentStep].content,
609 610 611 612 613 614
              ),
              _buildVerticalControls(),
            ],
          ),
        ),
      ],
615 616 617 618 619 620 621 622 623 624 625 626 627 628
    );
  }

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
    assert(() {
      if (context.ancestorWidgetOfExactType(Stepper) != null)
        throw new FlutterError(
          'Steppers must not be nested. The material specification advises '
          'that one should avoid embedding steppers within steppers. '
          'https://material.google.com/components/steppers.html#steppers-usage\n'
        );
      return true;
629
    }());
630 631
    assert(widget.type != null);
    switch (widget.type) {
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
      case StepperType.vertical:
        return _buildVertical();
      case StepperType.horizontal:
        return _buildHorizontal();
    }
    return null;
  }
}

// Paints a triangle whose base is the bottom of the bounding rectangle and its
// top vertex the middle of its top.
class _TrianglePainter extends CustomPainter {
  _TrianglePainter({
    this.color
  });

  final Color color;

  @override
651
  bool hitTest(Offset point) => true; // Hitting the rectangle is fine enough.
652 653 654 655 656 657 658 659 660 661 662

  @override
  bool shouldRepaint(_TrianglePainter oldPainter) {
    return oldPainter.color != color;
  }

  @override
  void paint(Canvas canvas, Size size) {
    final double base = size.width;
    final double halfBase = size.width / 2.0;
    final double height = size.height;
663 664 665 666
    final List<Offset> points = <Offset>[
      new Offset(0.0, height),
      new Offset(base, height),
      new Offset(halfBase, 0.0),
667 668 669 670
    ];

    canvas.drawPath(
      new Path()..addPolygon(points, true),
671
      new Paint()..color = color,
672 673 674
    );
  }
}