stepper.dart 25.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/widgets.dart';

7 8
import 'button_style.dart';
import 'color_scheme.dart';
9 10 11 12 13
import 'colors.dart';
import 'debug.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
14
import 'material_localizations.dart';
15 16
import 'material_state.dart';
import 'text_button.dart';
17
import 'text_theme.dart';
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import 'theme.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,
34

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

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

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

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

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

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

58
/// Container for all the information necessary to build a Stepper widget's
59
/// forward and backward controls for any given step.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
///
/// Used by [Stepper.controlsBuilder].
@immutable
class ControlsDetails {
  /// Creates a set of details describing the Stepper.
  const ControlsDetails({
    required this.currentStep,
    required this.stepIndex,
    this.onStepCancel,
    this.onStepContinue,
  });
  /// Index that is active for the surrounding [Stepper] widget. This may be
  /// different from [stepIndex] if the user has just changed steps and we are
  /// currently animating toward that step.
  final int currentStep;

  /// Index of the step for which these controls are being built. This is
  /// not necessarily the active index, if the user has just changed steps and
  /// this step is animating away. To determine whether a given builder is building
  /// the active step or the step being navigated away from, see [isActive].
  final int stepIndex;

  /// 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;

  /// True if the indicated step is also the current active step. If the user has
  /// just activated the transition to a new step, some [Stepper.type] values will
  /// lead to both steps being rendered for the duration of the animation shifting
  /// between steps.
  bool get isActive => currentStep == stepIndex;
}

/// A builder that creates a widget given the two callbacks `onStepContinue` and
/// `onStepCancel`.
///
/// Used by [Stepper.controlsBuilder].
///
/// See also:
///
///  * [WidgetBuilder], which is similar but only takes a [BuildContext].
typedef ControlsWidgetBuilder = Widget Function(BuildContext context, ControlsDetails details);

109
const TextStyle _kStepStyle = TextStyle(
110
  fontSize: 12.0,
111
  color: Colors.white,
112
);
113
const Color _kErrorLight = Colors.red;
114
final Color _kErrorDark = Colors.red.shade400;
115 116 117
const Color _kCircleActiveLight = Colors.white;
const Color _kCircleActiveDark = Colors.black87;
const Color _kDisabledLight = Colors.black38;
118
const Color _kDisabledDark = Colors.white38;
119
const double _kStepSize = 24.0;
Josh Soref's avatar
Josh Soref committed
120
const double _kTriangleHeight = _kStepSize * 0.866025; // Triangle height. sqrt(3.0) / 2.0
121 122 123 124 125 126 127 128

/// 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]
129
///  * <https://material.io/archive/guidelines/components/steppers.html>
130
@immutable
131 132 133 134
class Step {
  /// Creates a step for a [Stepper].
  ///
  /// The [title], [content], and [state] arguments must not be null.
135
  const Step({
136
    required this.title,
137
    this.subtitle,
138
    required this.content,
139 140
    this.state = StepState.indexed,
    this.isActive = false,
141 142 143
  }) : assert(title != null),
       assert(content != null),
       assert(state != null);
144 145 146 147 148 149 150 151

  /// 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.
152
  final Widget? subtitle;
153 154 155 156 157 158

  /// 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;

159
  /// The state of the step which determines the styling of its components
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  /// 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.
///
176 177 178
/// {@tool dartpad}
/// An example the shows how to use the [Stepper], and the [Stepper] UI
/// appearance.
179
///
180
/// ** See code in examples/api/lib/material/stepper/stepper.0.dart **
181 182
/// {@end-tool}
///
183 184 185
/// See also:
///
///  * [Step]
186
///  * <https://material.io/archive/guidelines/components/steppers.html>
187 188 189 190 191 192 193 194
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.
195
  const Stepper({
196 197
    Key? key,
    required this.steps,
198
    this.physics,
199 200
    this.type = StepperType.vertical,
    this.currentStep = 0,
201 202
    this.onStepTapped,
    this.onStepContinue,
203
    this.onStepCancel,
204
    this.controlsBuilder,
205
    this.elevation,
206
    this.margin,
207 208 209 210 211
  }) : assert(steps != null),
       assert(type != null),
       assert(currentStep != null),
       assert(0 <= currentStep && currentStep < steps.length),
       super(key: key);
212 213 214 215 216 217

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

218 219 220 221 222 223 224
  /// How the stepper's scroll view should respond to user input.
  ///
  /// For example, determines how the scroll view continues to
  /// animate after the user stops dragging the scroll view.
  ///
  /// If the stepper is contained within another scrollable it
  /// can be helpful to set this property to [ClampingScrollPhysics].
225
  final ScrollPhysics? physics;
226

227 228 229 230 231 232 233 234 235 236 237
  /// 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.
238
  final ValueChanged<int>? onStepTapped;
239 240 241 242

  /// The callback called when the 'continue' button is tapped.
  ///
  /// If null, the 'continue' button will be disabled.
243
  final VoidCallback? onStepContinue;
244 245 246 247

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

250 251 252 253
  /// The callback for creating custom controls.
  ///
  /// If null, the default controls from the current theme will be used.
  ///
254 255 256 257 258
  /// This callback which takes in a context and a [ControlsDetails] object, which
  /// contains step information and two functions: [onStepContinue] and [onStepCancel].
  /// These can be used to control the stepper. For example, reading the
  /// [ControlsDetails.currentStep] value within the callback can change the text
  /// of the continue or cancel button depending on which step users are at.
259
  ///
260
  /// {@tool dartpad}
261 262
  /// Creates a stepper control with custom buttons.
  ///
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return Stepper(
  ///     controlsBuilder:
  ///       (BuildContext context, ControlsDetails details) {
  ///          return Row(
  ///            children: <Widget>[
  ///              TextButton(
  ///                onPressed: details.onStepContinue,
  ///                child: Text('Continue to Step ${details.stepIndex + 1}'),
  ///              ),
  ///              TextButton(
  ///                onPressed: details.onStepCancel,
  ///                child: Text('Back to Step ${details.stepIndex - 1}'),
  ///              ),
  ///            ],
  ///          );
  ///       },
  ///     steps: const <Step>[
  ///       Step(
  ///         title: Text('A'),
  ///         content: SizedBox(
  ///           width: 100.0,
  ///           height: 100.0,
  ///         ),
  ///       ),
  ///       Step(
  ///         title: Text('B'),
  ///         content: SizedBox(
  ///           width: 100.0,
  ///           height: 100.0,
  ///         ),
  ///       ),
  ///     ],
  ///   );
  /// }
  /// ```
300
  /// ** See code in examples/api/lib/material/stepper/stepper.controls_builder.0.dart **
301
  /// {@end-tool}
302
  final ControlsWidgetBuilder? controlsBuilder;
303

304 305 306
  /// The elevation of this stepper's [Material] when [type] is [StepperType.horizontal].
  final double? elevation;

307 308 309
  /// custom margin on vertical stepper.
  final EdgeInsetsGeometry? margin;

310
  @override
311
  State<Stepper> createState() => _StepperState();
312 313
}

314
class _StepperState extends State<Stepper> with TickerProviderStateMixin {
315
  late List<GlobalKey> _keys;
316
  final Map<int, StepState> _oldStates = <int, StepState>{};
317 318 319 320

  @override
  void initState() {
    super.initState();
321
    _keys = List<GlobalKey>.generate(
322
      widget.steps.length,
323
      (int i) => GlobalKey(),
324 325
    );

326 327
    for (int i = 0; i < widget.steps.length; i += 1)
      _oldStates[i] = widget.steps[i].state;
328 329 330
  }

  @override
331 332 333
  void didUpdateWidget(Stepper oldWidget) {
    super.didUpdateWidget(oldWidget);
    assert(widget.steps.length == oldWidget.steps.length);
334

335 336
    for (int i = 0; i < oldWidget.steps.length; i += 1)
      _oldStates[i] = oldWidget.steps[i].state;
337 338 339 340 341 342 343
  }

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

  bool _isLast(int index) {
344
    return widget.steps.length - 1 == index;
345 346 347
  }

  bool _isCurrent(int index) {
348
    return widget.currentStep == index;
349 350 351
  }

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

  Widget _buildLine(bool visible) {
356
    return Container(
357 358
      width: visible ? 1.0 : 0.0,
      height: 16.0,
359
      color: Colors.grey.shade400,
360 361 362 363
    );
  }

  Widget _buildCircleChild(int index, bool oldState) {
364
    final StepState state = oldState ? _oldStates[index]! : widget.steps[index].state;
365
    final bool isDarkActive = _isDark() && widget.steps[index].isActive;
366 367 368 369
    assert(state != null);
    switch (state) {
      case StepState.indexed:
      case StepState.disabled:
370
        return Text(
371
          '${index + 1}',
372
          style: isDarkActive ? _kStepStyle.copyWith(color: Colors.black87) : _kStepStyle,
373 374
        );
      case StepState.editing:
375
        return Icon(
376
          Icons.edit,
377
          color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
378
          size: 18.0,
379 380
        );
      case StepState.complete:
381
        return Icon(
382
          Icons.check,
383
          color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
384
          size: 18.0,
385 386
        );
      case StepState.error:
387
        return const Text('!', style: _kStepStyle);
388 389 390 391
    }
  }

  Color _circleColor(int index) {
392
    final ColorScheme colorScheme = Theme.of(context).colorScheme;
393
    if (!_isDark()) {
394
      return widget.steps[index].isActive ? colorScheme.primary : colorScheme.onSurface.withOpacity(0.38);
395
    } else {
396
      return widget.steps[index].isActive ? colorScheme.secondary : colorScheme.background;
397 398 399 400
    }
  }

  Widget _buildCircle(int index, bool oldState) {
401
    return Container(
402 403 404
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      width: _kStepSize,
      height: _kStepSize,
405
      child: AnimatedContainer(
406 407
        curve: Curves.fastOutSlowIn,
        duration: kThemeAnimationDuration,
408
        decoration: BoxDecoration(
409
          color: _circleColor(index),
410
          shape: BoxShape.circle,
411
        ),
412
        child: Center(
413
          child: _buildCircleChild(index, oldState && widget.steps[index].state == StepState.error),
414 415
        ),
      ),
416 417 418 419
    );
  }

  Widget _buildTriangle(int index, bool oldState) {
420
    return Container(
421 422 423
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      width: _kStepSize,
      height: _kStepSize,
424 425
      child: Center(
        child: SizedBox(
426 427
          width: _kStepSize,
          height: _kTriangleHeight, // Height of 24dp-long-sided equilateral triangle.
428 429
          child: CustomPaint(
            painter: _TrianglePainter(
430
              color: _isDark() ? _kErrorDark : _kErrorLight,
431
            ),
432
            child: Align(
433
              alignment: const Alignment(0.0, 0.8), // 0.8 looks better than the geometrical 0.33.
434
              child: _buildCircleChild(index, oldState && widget.steps[index].state != StepState.error),
435 436 437 438
            ),
          ),
        ),
      ),
439 440 441 442
    );
  }

  Widget _buildIcon(int index) {
443
    if (widget.steps[index].state != _oldStates[index]) {
444
      return AnimatedCrossFade(
445 446
        firstChild: _buildCircle(index, true),
        secondChild: _buildTriangle(index, true),
447 448
        firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
        secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
449
        sizeCurve: Curves.fastOutSlowIn,
450
        crossFadeState: widget.steps[index].state == StepState.error ? CrossFadeState.showSecond : CrossFadeState.showFirst,
451 452 453
        duration: kThemeAnimationDuration,
      );
    } else {
454
      if (widget.steps[index].state != StepState.error)
455 456 457 458 459 460
        return _buildCircle(index, false);
      else
        return _buildTriangle(index, false);
    }
  }

461
  Widget _buildVerticalControls(int stepIndex) {
462
    if (widget.controlsBuilder != null)
463 464 465 466 467 468 469 470 471
      return widget.controlsBuilder!(
        context,
        ControlsDetails(
          currentStep: widget.currentStep,
          onStepContinue: widget.onStepContinue,
          onStepCancel: widget.onStepCancel,
          stepIndex: stepIndex,
        ),
      );
472

473
    final Color cancelColor;
474
    switch (Theme.of(context).brightness) {
475 476 477 478 479 480 481 482
      case Brightness.light:
        cancelColor = Colors.black54;
        break;
      case Brightness.dark:
        cancelColor = Colors.white70;
        break;
    }

483
    final ThemeData themeData = Theme.of(context);
484
    final ColorScheme colorScheme = themeData.colorScheme;
485
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
486

487 488 489
    const OutlinedBorder buttonShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2)));
    const EdgeInsets buttonPadding = EdgeInsets.symmetric(horizontal: 16.0);

490
    return Container(
491
      margin: const EdgeInsets.only(top: 16.0),
492
      child: ConstrainedBox(
493
        constraints: const BoxConstraints.tightFor(height: 48.0),
494
        child: Row(
495 496 497
          // The Material spec no longer includes a Stepper widget. The continue
          // and cancel button styles have been configured to match the original
          // version of this widget.
498
          children: <Widget>[
499
            TextButton(
500
              onPressed: widget.onStepContinue,
501
              style: ButtonStyle(
502
                foregroundColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
503 504
                  return states.contains(MaterialState.disabled) ? null : (_isDark() ? colorScheme.onSurface : colorScheme.onPrimary);
                }),
505
                backgroundColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
506 507 508 509 510
                  return _isDark() || states.contains(MaterialState.disabled) ? null : colorScheme.primary;
                }),
                padding: MaterialStateProperty.all<EdgeInsetsGeometry>(buttonPadding),
                shape: MaterialStateProperty.all<OutlinedBorder>(buttonShape),
              ),
511
              child: Text(localizations.continueButtonLabel),
512
            ),
513
            Container(
514
              margin: const EdgeInsetsDirectional.only(start: 8.0),
515
              child: TextButton(
516
                onPressed: widget.onStepCancel,
517 518 519 520 521
                style: TextButton.styleFrom(
                  primary: cancelColor,
                  padding: buttonPadding,
                  shape: buttonShape,
                ),
522
                child: Text(localizations.cancelButtonLabel),
523 524 525 526 527
              ),
            ),
          ],
        ),
      ),
528 529 530 531
    );
  }

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

535 536
    assert(widget.steps[index].state != null);
    switch (widget.steps[index].state) {
537 538 539
      case StepState.indexed:
      case StepState.editing:
      case StepState.complete:
540
        return textTheme.bodyText1!;
541
      case StepState.disabled:
542
        return textTheme.bodyText1!.copyWith(
543
          color: _isDark() ? _kDisabledDark : _kDisabledLight,
544 545
        );
      case StepState.error:
546
        return textTheme.bodyText1!.copyWith(
547
          color: _isDark() ? _kErrorDark : _kErrorLight,
548 549 550 551 552
        );
    }
  }

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

556 557
    assert(widget.steps[index].state != null);
    switch (widget.steps[index].state) {
558 559 560
      case StepState.indexed:
      case StepState.editing:
      case StepState.complete:
561
        return textTheme.caption!;
562
      case StepState.disabled:
563
        return textTheme.caption!.copyWith(
564
          color: _isDark() ? _kDisabledDark : _kDisabledLight,
565 566
        );
      case StepState.error:
567
        return textTheme.caption!.copyWith(
568
          color: _isDark() ? _kErrorDark : _kErrorLight,
569 570 571 572 573
        );
    }
  }

  Widget _buildHeaderText(int index) {
574
    return Column(
575 576
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
577 578 579 580 581 582 583 584 585 586 587 588 589 590
      children: <Widget>[
        AnimatedDefaultTextStyle(
          style: _titleStyle(index),
          duration: kThemeAnimationDuration,
          curve: Curves.fastOutSlowIn,
          child: widget.steps[index].title,
        ),
        if (widget.steps[index].subtitle != null)
          Container(
            margin: const EdgeInsets.only(top: 2.0),
            child: AnimatedDefaultTextStyle(
              style: _subtitleStyle(index),
              duration: kThemeAnimationDuration,
              curve: Curves.fastOutSlowIn,
591
              child: widget.steps[index].subtitle!,
592 593 594
            ),
          ),
      ],
595 596 597 598
    );
  }

  Widget _buildVerticalHeader(int index) {
599
    return Container(
600
      margin: const EdgeInsets.symmetric(horizontal: 24.0),
601
      child: Row(
602
        children: <Widget>[
603
          Column(
604 605 606 607 608 609
            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)),
610
            ],
611
          ),
612 613 614 615
          Expanded(
            child: Container(
              margin: const EdgeInsetsDirectional.only(start: 12.0),
              child: _buildHeaderText(index),
616
            ),
617 618 619
          ),
        ],
      ),
620 621 622 623
    );
  }

  Widget _buildVerticalBody(int index) {
624
    return Stack(
625
      children: <Widget>[
626
        PositionedDirectional(
627
          start: 24.0,
628 629
          top: 0.0,
          bottom: 0.0,
630
          child: SizedBox(
631
            width: 24.0,
632 633
            child: Center(
              child: SizedBox(
634
                width: _isLast(index) ? 0.0 : 1.0,
635
                child: Container(
636
                  color: Colors.grey.shade400,
637 638 639 640
                ),
              ),
            ),
          ),
641
        ),
642 643 644
        AnimatedCrossFade(
          firstChild: Container(height: 0.0),
          secondChild: Container(
645
            margin: widget.margin ?? const EdgeInsetsDirectional.only(
646 647
              start: 60.0,
              end: 24.0,
648
              bottom: 24.0,
649
            ),
650
            child: Column(
651
              children: <Widget>[
652
                widget.steps[index].content,
653
                _buildVerticalControls(index),
654 655
              ],
            ),
656
          ),
657 658
          firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
          secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
659 660 661
          sizeCurve: Curves.fastOutSlowIn,
          crossFadeState: _isCurrent(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst,
          duration: kThemeAnimationDuration,
662 663
        ),
      ],
664 665 666 667
    );
  }

  Widget _buildVertical() {
668
    return ListView(
669
      shrinkWrap: true,
670
      physics: widget.physics,
671 672 673 674 675 676 677 678 679 680
      children: <Widget>[
        for (int i = 0; i < widget.steps.length; i += 1)
          Column(
            key: _keys[i],
            children: <Widget>[
              InkWell(
                onTap: widget.steps[i].state != StepState.disabled ? () {
                  // In the vertical case we need to scroll to the newly tapped
                  // step.
                  Scrollable.ensureVisible(
681
                    _keys[i].currentContext!,
682 683 684 685
                    curve: Curves.fastOutSlowIn,
                    duration: kThemeAnimationDuration,
                  );

686
                  widget.onStepTapped?.call(i);
687
                } : null,
688
                canRequestFocus: widget.steps[i].state != StepState.disabled,
689 690 691 692 693 694
                child: _buildVerticalHeader(i),
              ),
              _buildVerticalBody(i),
            ],
          ),
      ],
695 696 697 698
    );
  }

  Widget _buildHorizontal() {
699 700
    final List<Widget> children = <Widget>[
      for (int i = 0; i < widget.steps.length; i += 1) ...<Widget>[
701
        InkResponse(
702
          onTap: widget.steps[i].state != StepState.disabled ? () {
703
            widget.onStepTapped?.call(i);
704
          } : null,
705
          canRequestFocus: widget.steps[i].state != StepState.disabled,
706
          child: Row(
707
            children: <Widget>[
708
              SizedBox(
709
                height: 72.0,
710
                child: Center(
711 712
                  child: _buildIcon(i),
                ),
713
              ),
714
              Container(
715
                margin: const EdgeInsetsDirectional.only(start: 12.0),
716 717 718 719 720
                child: _buildHeaderText(i),
              ),
            ],
          ),
        ),
721
        if (!_isLast(i))
722 723
          Expanded(
            child: Container(
724 725
              margin: const EdgeInsets.symmetric(horizontal: 8.0),
              height: 1.0,
726
              color: Colors.grey.shade400,
727 728
            ),
          ),
729 730
      ],
    ];
731

732 733 734 735 736 737 738 739 740 741 742
    final List<Widget> stepPanels = <Widget>[];
    for (int i = 0; i < widget.steps.length; i += 1) {
      stepPanels.add(
        Visibility(
          maintainState: true,
          visible: i == widget.currentStep,
          child: widget.steps[i].content,
        ),
      );
    }

743
    return Column(
744
      children: <Widget>[
745
        Material(
746
          elevation: widget.elevation ?? 2,
747
          child: Container(
748
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
749
            child: Row(
750 751 752
              children: children,
            ),
          ),
753
        ),
754 755
        Expanded(
          child: ListView(
TheBirb's avatar
TheBirb committed
756
            physics: widget.physics,
757 758
            padding: const EdgeInsets.all(24.0),
            children: <Widget>[
759
              AnimatedSize(
760 761
                curve: Curves.fastOutSlowIn,
                duration: kThemeAnimationDuration,
762
                child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: stepPanels),
763
              ),
764
              _buildVerticalControls(widget.currentStep),
765 766 767 768
            ],
          ),
        ),
      ],
769 770 771 772 773 774
    );
  }

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
775
    assert(debugCheckHasMaterialLocalizations(context));
776
    assert(() {
777
      if (context.findAncestorWidgetOfExactType<Stepper>() != null)
778
        throw FlutterError(
779 780 781
          'Steppers must not be nested.\n'
          'The material specification advises that one should avoid embedding '
          'steppers within steppers. '
782
          'https://material.io/archive/guidelines/components/steppers.html#steppers-usage',
783 784
        );
      return true;
785
    }());
786 787
    assert(widget.type != null);
    switch (widget.type) {
788 789 790 791 792 793 794 795 796 797 798 799
      case StepperType.vertical:
        return _buildVertical();
      case StepperType.horizontal:
        return _buildHorizontal();
    }
  }
}

// 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({
800
    required this.color,
801 802 803 804 805
  });

  final Color color;

  @override
806
  bool hitTest(Offset point) => true; // Hitting the rectangle is fine enough.
807 808 809 810 811 812 813 814 815 816 817

  @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;
818
    final List<Offset> points = <Offset>[
819 820 821
      Offset(0.0, height),
      Offset(base, height),
      Offset(halfBase, 0.0),
822 823 824
    ];

    canvas.drawPath(
825 826
      Path()..addPolygon(points, true),
      Paint()..color = color,
827 828 829
    );
  }
}