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

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/rendering.dart';
7
import 'package:flutter/widgets.dart';
8

9
import 'constants.dart';
10
import 'elevation_overlay.dart';
11
import 'theme.dart';
12

13 14
/// Signature for the callback used by ink effects to obtain the rectangle for the effect.
///
15
/// Used by [InkHighlight] and [InkSplash], for example.
16
typedef RectCallback = Rect Function();
17 18 19

/// The various kinds of material in material design. Used to
/// configure the default behavior of [Material] widgets.
20 21
///
/// See also:
22
///
23
///  * [Material], in particular [Material.type].
24
///  * [kMaterialEdges]
25
enum MaterialType {
26
  /// Rectangle using default theme canvas color.
27 28 29 30
  canvas,

  /// Rounded edges, card theme color.
  card,
31

32 33 34
  /// A circle, no color by default (used for floating action buttons).
  circle,

35
  /// Rounded edges, no color by default (used for [MaterialButton] buttons).
36 37 38
  button,

  /// A transparent piece of material that draws ink splashes and highlights.
39 40 41 42 43 44 45 46 47
  ///
  /// While the material metaphor describes child widgets as printed on the
  /// material itself and do not hide ink effects, in practice the [Material]
  /// widget draws child widgets on top of the ink effects.
  /// A [Material] with type transparency can be placed on top of opaque widgets
  /// to show ink effects on top of them.
  ///
  /// Prefer using the [Ink] widget for showing ink effects on top of opaque
  /// widgets.
48
  transparency
49 50
}

51 52 53 54 55 56
/// The border radii used by the various kinds of material in material design.
///
/// See also:
///
///  * [MaterialType]
///  * [Material]
57
final Map<MaterialType, BorderRadius> kMaterialEdges = <MaterialType, BorderRadius>{
58
  MaterialType.canvas: null,
59
  MaterialType.card: BorderRadius.circular(2.0),
60
  MaterialType.circle: null,
61
  MaterialType.button: BorderRadius.circular(2.0),
62
  MaterialType.transparency: null,
63 64
};

65 66 67
/// An interface for creating [InkSplash]s and [InkHighlight]s on a material.
///
/// Typically obtained via [Material.of].
68
abstract class MaterialInkController {
69
  /// The color of the material.
70 71
  Color get color;

72
  /// The ticker provider used by the controller.
73
  ///
74 75 76 77 78
  /// Ink features that are added to this controller with [addInkFeature] should
  /// use this vsync to drive their animations.
  TickerProvider get vsync;

  /// Add an [InkFeature], such as an [InkSplash] or an [InkHighlight].
79
  ///
80
  /// The ink feature will paint as part of this controller.
81
  void addInkFeature(InkFeature feature);
82 83 84

  /// Notifies the controller that one of its ink features needs to repaint.
  void markNeedsPaint();
85 86
}

87 88
/// A piece of material.
///
89 90
/// The Material widget is responsible for:
///
91 92 93
/// 1. Clipping: If [clipBehavior] is not [Clip.none], Material clips its widget
///    sub-tree to the shape specified by [shape], [type], and [borderRadius].
///    By default, [clipBehavior] is [Clip.none] for performance considerations.
94 95 96 97 98 99 100
/// 2. Elevation: Material elevates its widget sub-tree on the Z axis by
///    [elevation] pixels, and draws the appropriate shadow.
/// 3. Ink effects: Material shows ink effects implemented by [InkFeature]s
///    like [InkSplash] and [InkHighlight] below its children.
///
/// ## The Material Metaphor
///
101 102 103
/// Material is the central metaphor in material design. Each piece of material
/// exists at a given elevation, which influences how that piece of material
/// visually relates to other pieces of material and how that material casts
104
/// shadows.
105 106 107 108 109 110
///
/// Most user interface elements are either conceptually printed on a piece of
/// material or themselves made of material. Material reacts to user input using
/// [InkSplash] and [InkHighlight] effects. To trigger a reaction on the
/// material, use a [MaterialInkController] obtained via [Material.of].
///
111
/// In general, the features of a [Material] should not change over time (e.g. a
112
/// [Material] should not change its [color], [shadowColor] or [type]).
113 114 115 116
/// Changes to [elevation] and [shadowColor] are animated for [animationDuration].
/// Changes to [shape] are animated if [type] is not [MaterialType.transparency]
/// and [ShapeBorder.lerp] between the previous and next [shape] values is
/// supported. Shape changes are also animated for [animationDuration].
117
///
118 119 120
///
/// ## Shape
///
121
/// The shape for material is determined by [shape], [type], and [borderRadius].
122
///
123 124 125 126 127
///  - If [shape] is non null, it determines the shape.
///  - If [shape] is null and [borderRadius] is non null, the shape is a
///    rounded rectangle, with corners specified by [borderRadius].
///  - If [shape] and [borderRadius] are null, [type] determines the
///    shape as follows:
128 129 130 131 132 133 134 135
///    - [MaterialType.canvas]: the default material shape is a rectangle.
///    - [MaterialType.card]: the default material shape is a rectangle with
///      rounded edges. The edge radii is specified by [kMaterialEdges].
///    - [MaterialType.circle]: the default material shape is a circle.
///    - [MaterialType.button]: the default material shape is a rectangle with
///      rounded edges. The edge radii is specified by [kMaterialEdges].
///    - [MaterialType.transparency]: the default material shape is a rectangle.
///
136 137 138 139
/// ## Border
///
/// If [shape] is not null, then its border will also be painted (if any).
///
140
/// ## Layout change notifications
141
///
Ian Hickson's avatar
Ian Hickson committed
142 143 144 145 146 147 148 149
/// If the layout changes (e.g. because there's a list on the material, and it's
/// been scrolled), a [LayoutChangedNotification] must be dispatched at the
/// relevant subtree. This in particular means that transitions (e.g.
/// [SlideTransition]) should not be placed inside [Material] widgets so as to
/// move subtrees that contain [InkResponse]s, [InkWell]s, [Ink]s, or other
/// widgets that use the [InkFeature] mechanism. Otherwise, in-progress ink
/// features (e.g., ink splashes and ink highlights) won't move to account for
/// the new layout.
150 151 152
///
/// See also:
///
153
///  * [MergeableMaterial], a piece of material that can split and re-merge.
154
///  * [Card], a wrapper for a [Material] of [type] [MaterialType.card].
155
///  * <https://material.io/design/>
156
class Material extends StatefulWidget {
157 158
  /// Creates a piece of material.
  ///
159 160 161
  /// The [type], [elevation], [shadowColor], [borderOnForeground],
  /// [clipBehavior], and [animationDuration] arguments must not be null.
  /// Additionally, [elevation] must be non-negative.
162
  ///
163
  /// If a [shape] is specified, then the [borderRadius] property must be
164 165 166 167
  /// null and the [type] property must not be [MaterialType.circle]. If the
  /// [borderRadius] is specified, then the [type] property must not be
  /// [MaterialType.circle]. In both cases, these restrictions are intended to
  /// catch likely errors.
168
  const Material({
169
    Key key,
170 171
    this.type = MaterialType.canvas,
    this.elevation = 0.0,
172
    this.color,
173
    this.shadowColor = const Color(0xFF000000),
174
    this.textStyle,
175
    this.borderRadius,
176
    this.shape,
177
    this.borderOnForeground = true,
178
    this.clipBehavior = Clip.none,
179
    this.animationDuration = kThemeChangeDuration,
180
    this.child,
181
  }) : assert(type != null),
182
       assert(elevation != null && elevation >= 0.0),
183
       assert(shadowColor != null),
184
       assert(!(shape != null && borderRadius != null)),
185
       assert(animationDuration != null),
186
       assert(!(identical(type, MaterialType.circle) && (borderRadius != null || shape != null))),
187
       assert(borderOnForeground != null),
188
       assert(clipBehavior != null),
189
       super(key: key);
190

191
  /// The widget below this widget in the tree.
192 193
  ///
  /// {@macro flutter.widgets.child}
194
  final Widget child;
195

196 197 198
  /// The kind of material to show (e.g., card or canvas). This
  /// affects the shape of the widget, the roundness of its corners if
  /// the shape is rectangular, and the default color.
199
  final MaterialType type;
200

201
  /// {@template flutter.material.material.elevation}
202 203
  /// The z-coordinate at which to place this material relative to its parent.
  ///
204 205
  /// This controls the size of the shadow below the material and the opacity
  /// of the elevation overlay color if it is applied.
206
  ///
207
  /// If this is non-zero, the contents of the material are clipped, because the
208 209
  /// widget conceptually defines an independent printed piece of material.
  ///
210 211
  /// Defaults to 0. Changing this value will cause the shadow and the elevation
  /// overlay to animate over [animationDuration].
212 213
  ///
  /// The value is non-negative.
214 215 216
  ///
  /// See also:
  ///
217 218 219
  ///  * [ThemeData.applyElevationOverlayColor] which controls the whether
  ///    an overlay color will be applied to indicate elevation.
  ///  * [color] which may have an elevation overlay applied.
220
  ///
221
  /// {@endtemplate}
222
  final double elevation;
223

224
  /// The color to paint the material.
225 226 227
  ///
  /// Must be opaque. To create a transparent piece of material, use
  /// [MaterialType.transparency].
228
  ///
229
  /// To support dark themes, if the surrounding
230 231 232
  /// [ThemeData.applyElevationOverlayColor] is true then a semi-transparent
  /// overlay color will be composited on top this color to indicate
  /// the elevation.
233
  ///
234
  /// By default, the color is derived from the [type] of material.
235
  final Color color;
236

237 238 239 240 241
  /// The color to paint the shadow below the material.
  ///
  /// Defaults to fully opaque black.
  final Color shadowColor;

242
  /// The typographical style to use for text within this material.
243
  final TextStyle textStyle;
244

245 246 247 248 249 250 251
  /// Defines the material's shape as well its shadow.
  ///
  /// If shape is non null, the [borderRadius] is ignored and the material's
  /// clip boundary and shadow are defined by the shape.
  ///
  /// A shadow is only displayed if the [elevation] is greater than
  /// zero.
252 253
  final ShapeBorder shape;

254 255 256 257 258 259
  /// Whether to paint the [shape] border in front of the [child].
  ///
  /// The default value is true.
  /// If false, the border will be painted behind the [child].
  final bool borderOnForeground;

260 261 262 263 264 265
  /// {@template flutter.widgets.Clip}
  /// The content will be clipped (or not) according to this option.
  ///
  /// See the enum [Clip] for details of all possible options and their common
  /// use cases.
  /// {@endtemplate}
266 267
  ///
  /// Defaults to [Clip.none], and must not be null.
268 269
  final Clip clipBehavior;

270
  /// Defines the duration of animated changes for [shape], [elevation],
271
  /// [shadowColor] and the elevation overlay if it is applied.
272 273 274 275
  ///
  /// The default value is [kThemeChangeDuration].
  final Duration animationDuration;

276 277 278
  /// If non-null, the corners of this box are rounded by this
  /// [BorderRadiusGeometry] value.
  ///
279 280 281
  /// Otherwise, the corners specified for the current [type] of material are
  /// used.
  ///
282 283
  /// If [shape] is non null then the border radius is ignored.
  ///
284
  /// Must be null if [type] is [MaterialType.circle].
285
  final BorderRadiusGeometry borderRadius;
286

287 288
  /// The ink controller from the closest instance of this class that
  /// encloses the given context.
289 290 291 292 293 294
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// MaterialInkController inkController = Material.of(context);
  /// ```
295
  static MaterialInkController of(BuildContext context) {
296
    final _RenderInkFeatures result = context.findAncestorRenderObjectOfType<_RenderInkFeatures>();
297 298 299
    return result;
  }

300
  @override
301
  _MaterialState createState() => _MaterialState();
302

303
  @override
304 305
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
306 307
    properties.add(EnumProperty<MaterialType>('type', type));
    properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0));
308 309
    properties.add(ColorProperty('color', color, defaultValue: null));
    properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: const Color(0xFF000000)));
310
    textStyle?.debugFillProperties(properties, prefix: 'textStyle.');
311
    properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
312
    properties.add(DiagnosticsProperty<bool>('borderOnForeground', borderOnForeground, defaultValue: true));
313
    properties.add(DiagnosticsProperty<BorderRadiusGeometry>('borderRadius', borderRadius, defaultValue: null));
314
  }
315 316 317

  /// The default radius of an ink splash in logical pixels.
  static const double defaultSplashRadius = 35.0;
318 319
}

320
class _MaterialState extends State<Material> with TickerProviderStateMixin {
321
  final GlobalKey _inkFeatureRenderer = GlobalKey(debugLabel: 'ink renderer');
322

323
  Color _getBackgroundColor(BuildContext context) {
324 325 326 327 328 329 330 331 332 333 334 335 336
    final ThemeData theme = Theme.of(context);
    Color color = widget.color;
    if (color == null) {
      switch (widget.type) {
        case MaterialType.canvas:
          color = theme.canvasColor;
          break;
        case MaterialType.card:
          color = theme.cardColor;
          break;
        default:
          break;
      }
337
    }
338
    return color;
339 340
  }

341
  @override
342
  Widget build(BuildContext context) {
343
    final Color backgroundColor = _getBackgroundColor(context);
344 345 346 347 348 349 350
    assert(
      backgroundColor != null || widget.type == MaterialType.transparency,
      'If Material type is not MaterialType.transparency, a color must '
      'either be passed in through the `color` property, or be defined '
      'in the theme (ex. canvasColor != null if type is set to '
      'MaterialType.canvas)'
    );
351
    Widget contents = widget.child;
352
    if (contents != null) {
353
      contents = AnimatedDefaultTextStyle(
354
        style: widget.textStyle ?? Theme.of(context).textTheme.bodyText2,
355
        duration: widget.animationDuration,
356
        child: contents,
357 358
      );
    }
359
    contents = NotificationListener<LayoutChangedNotification>(
360
      onNotification: (LayoutChangedNotification notification) {
361
        final _RenderInkFeatures renderer = _inkFeatureRenderer.currentContext.findRenderObject() as _RenderInkFeatures;
362
        renderer._didChangeLayout();
363
        return false;
364
      },
365
      child: _InkFeatures(
366 367
        key: _inkFeatureRenderer,
        color: backgroundColor,
368 369
        child: contents,
        vsync: this,
370
      ),
371
    );
372

Josh Soref's avatar
Josh Soref committed
373
    // PhysicalModel has a temporary workaround for a performance issue that
374 375
    // speeds up rectangular non transparent material (the workaround is to
    // skip the call to ui.Canvas.saveLayer if the border radius is 0).
Josh Soref's avatar
Josh Soref committed
376
    // Until the saveLayer performance issue is resolved, we're keeping this
377 378
    // special case here for canvas material type that is using the default
    // shape (rectangle). We could go down this fast path for explicitly
Josh Soref's avatar
Josh Soref committed
379
    // specified rectangles (e.g shape RoundedRectangleBorder with radius 0, but
380 381 382
    // we choose not to as we want the change from the fast-path to the
    // slow-path to be noticeable in the construction site of Material.
    if (widget.type == MaterialType.canvas && widget.shape == null && widget.borderRadius == null) {
383
      return AnimatedPhysicalModel(
384
        curve: Curves.fastOutSlowIn,
385
        duration: widget.animationDuration,
386
        shape: BoxShape.rectangle,
387
        clipBehavior: widget.clipBehavior,
388 389
        borderRadius: BorderRadius.zero,
        elevation: widget.elevation,
390
        color: ElevationOverlay.applyOverlay(context, backgroundColor, widget.elevation),
391 392 393 394 395 396
        shadowColor: widget.shadowColor,
        animateColor: false,
        child: contents,
      );
    }

397 398
    final ShapeBorder shape = _getShape();

399 400 401 402 403 404 405 406
    if (widget.type == MaterialType.transparency) {
      return _transparentInterior(
        context: context,
        shape: shape,
        clipBehavior: widget.clipBehavior,
        contents: contents,
      );
    }
407

408
    return _MaterialInterior(
409
      curve: Curves.fastOutSlowIn,
410
      duration: widget.animationDuration,
411
      shape: shape,
412
      borderOnForeground: widget.borderOnForeground,
413
      clipBehavior: widget.clipBehavior,
414 415 416 417 418 419 420
      elevation: widget.elevation,
      color: backgroundColor,
      shadowColor: widget.shadowColor,
      child: contents,
    );
  }

421 422 423 424 425 426
  static Widget _transparentInterior({
    @required BuildContext context,
    @required ShapeBorder shape,
    @required Clip clipBehavior,
    @required Widget contents,
  }) {
427
    final _ShapeBorderPaint child = _ShapeBorderPaint(
428 429 430 431 432 433
      child: contents,
      shape: shape,
    );
    if (clipBehavior == Clip.none) {
      return child;
    }
434
    return ClipPath(
435
      child: child,
436 437 438 439
      clipper: ShapeBorderClipper(
        shape: shape,
        textDirection: Directionality.of(context),
      ),
440
      clipBehavior: clipBehavior,
441 442 443 444 445 446 447 448 449 450 451 452 453 454
    );
  }

  // Determines the shape for this Material.
  //
  // If a shape was specified, it will determine the shape.
  // If a borderRadius was specified, the shape is a rounded
  // rectangle.
  // Otherwise, the shape is determined by the widget type as described in the
  // Material class documentation.
  ShapeBorder _getShape() {
    if (widget.shape != null)
      return widget.shape;
    if (widget.borderRadius != null)
455
      return RoundedRectangleBorder(borderRadius: widget.borderRadius);
456 457 458
    switch (widget.type) {
      case MaterialType.canvas:
      case MaterialType.transparency:
459
        return const RoundedRectangleBorder();
460 461 462

      case MaterialType.card:
      case MaterialType.button:
463
        return RoundedRectangleBorder(
464
          borderRadius: widget.borderRadius ?? kMaterialEdges[widget.type],
465
        );
466

467 468 469
      case MaterialType.circle:
        return const CircleBorder();
    }
470
    return const RoundedRectangleBorder();
471 472 473
  }
}

474
class _RenderInkFeatures extends RenderProxyBox implements MaterialInkController {
475 476 477 478 479 480
  _RenderInkFeatures({
    RenderBox child,
    @required this.vsync,
    this.color,
  }) : assert(vsync != null),
       super(child);
481 482 483 484

  // This class should exist in a 1:1 relationship with a MaterialState object,
  // since there's no current support for dynamically changing the ticker
  // provider.
485
  @override
486
  final TickerProvider vsync;
487 488 489 490

  // This is here to satisfy the MaterialInkController contract.
  // The actual painting of this color is done by a Container in the
  // MaterialState build method.
491
  @override
492 493
  Color color;

494
  List<InkFeature> _inkFeatures;
495

496
  @override
497 498
  void addInkFeature(InkFeature feature) {
    assert(!feature._debugDisposed);
499
    assert(feature._controller == this);
500
    _inkFeatures ??= <InkFeature>[];
501 502 503 504 505 506
    assert(!_inkFeatures.contains(feature));
    _inkFeatures.add(feature);
    markNeedsPaint();
  }

  void _removeFeature(InkFeature feature) {
507
    assert(_inkFeatures != null);
508 509 510 511
    _inkFeatures.remove(feature);
    markNeedsPaint();
  }

512
  void _didChangeLayout() {
513
    if (_inkFeatures != null && _inkFeatures.isNotEmpty)
514 515 516
      markNeedsPaint();
  }

517
  @override
518
  bool hitTestSelf(Offset position) => true;
519

520
  @override
521
  void paint(PaintingContext context, Offset offset) {
522
    if (_inkFeatures != null && _inkFeatures.isNotEmpty) {
523 524 525
      final Canvas canvas = context.canvas;
      canvas.save();
      canvas.translate(offset.dx, offset.dy);
526
      canvas.clipRect(Offset.zero & size);
527
      for (final InkFeature inkFeature in _inkFeatures)
528 529 530 531 532 533 534
        inkFeature._paint(canvas);
      canvas.restore();
    }
    super.paint(context, offset);
  }
}

535
class _InkFeatures extends SingleChildRenderObjectWidget {
536 537 538 539 540 541
  const _InkFeatures({
    Key key,
    this.color,
    @required this.vsync,
    Widget child,
  }) : super(key: key, child: child);
542 543 544

  // This widget must be owned by a MaterialState, which must be provided as the vsync.
  // This relationship must be 1:1 and cannot change for the lifetime of the MaterialState.
545 546 547

  final Color color;

548 549
  final TickerProvider vsync;

550
  @override
551
  _RenderInkFeatures createRenderObject(BuildContext context) {
552
    return _RenderInkFeatures(
553
      color: color,
554
      vsync: vsync,
555 556
    );
  }
557

558
  @override
559
  void updateRenderObject(BuildContext context, _RenderInkFeatures renderObject) {
560
    renderObject.color = color;
561
    assert(vsync == renderObject.vsync);
562 563 564
  }
}

565 566
/// A visual reaction on a piece of [Material].
///
567 568 569
/// To add an ink feature to a piece of [Material], obtain the
/// [MaterialInkController] via [Material.of] and call
/// [MaterialInkController.addInkFeature].
570
abstract class InkFeature {
571
  /// Initializes fields for subclasses.
572
  InkFeature({
573 574
    @required MaterialInkController controller,
    @required this.referenceBox,
575
    this.onRemoved,
576 577
  }) : assert(controller != null),
       assert(referenceBox != null),
578
       _controller = controller as _RenderInkFeatures;
579

580 581 582 583
  /// The [MaterialInkController] associated with this [InkFeature].
  ///
  /// Typically used by subclasses to call
  /// [MaterialInkController.markNeedsPaint] when they need to repaint.
584
  MaterialInkController get controller => _controller;
585
  final _RenderInkFeatures _controller;
586 587

  /// The render box whose visual position defines the frame of reference for this ink feature.
588
  final RenderBox referenceBox;
589 590

  /// Called when the ink feature is no longer visible on the material.
591 592 593 594
  final VoidCallback onRemoved;

  bool _debugDisposed = false;

595
  /// Free up the resources associated with this ink feature.
596
  @mustCallSuper
597 598
  void dispose() {
    assert(!_debugDisposed);
599 600 601 602
    assert(() {
      _debugDisposed = true;
      return true;
    }());
603
    _controller._removeFeature(this);
604 605 606 607 608 609 610 611
    if (onRemoved != null)
      onRemoved();
  }

  void _paint(Canvas canvas) {
    assert(referenceBox.attached);
    assert(!_debugDisposed);
    // find the chain of renderers from us to the feature's referenceBox
612 613
    final List<RenderObject> descendants = <RenderObject>[referenceBox];
    RenderObject node = referenceBox;
614
    while (node != _controller) {
615
      node = node.parent as RenderObject;
616
      assert(node != null);
617
      descendants.add(node);
618 619
    }
    // determine the transform that gets our coordinate system to be like theirs
620
    final Matrix4 transform = Matrix4.identity();
621 622 623
    assert(descendants.length >= 2);
    for (int index = descendants.length - 1; index > 0; index -= 1)
      descendants[index].applyPaintTransform(descendants[index - 1], transform);
624 625 626
    paintFeature(canvas, transform);
  }

627 628 629
  /// Override this method to paint the ink feature.
  ///
  /// The transform argument gives the coordinate conversion from the coordinate
630
  /// system of the canvas to the coordinate system of the [referenceBox].
631
  @protected
632 633
  void paintFeature(Canvas canvas, Matrix4 transform);

634
  @override
635
  String toString() => describeIdentity(this);
636
}
637 638 639 640 641 642 643 644 645

/// An interpolation between two [ShapeBorder]s.
///
/// This class specializes the interpolation of [Tween] to use [ShapeBorder.lerp].
class ShapeBorderTween extends Tween<ShapeBorder> {
  /// Creates a [ShapeBorder] tween.
  ///
  /// the [begin] and [end] properties may be null; see [ShapeBorder.lerp] for
  /// the null handling semantics.
646
  ShapeBorderTween({ShapeBorder begin, ShapeBorder end}) : super(begin: begin, end: end);
647 648 649 650 651 652 653 654 655 656 657 658

  /// Returns the value this tween has at the given animation clock value.
  @override
  ShapeBorder lerp(double t) {
    return ShapeBorder.lerp(begin, end, t);
  }
}

/// The interior of non-transparent material.
///
/// Animates [elevation], [shadowColor], and [shape].
class _MaterialInterior extends ImplicitlyAnimatedWidget {
659 660 661 662 663
  /// Creates a const instance of [_MaterialInterior].
  ///
  /// The [child], [shape], [clipBehavior], [color], and [shadowColor] arguments
  /// must not be null. The [elevation] must be specified and greater than or
  /// equal to zero.
664 665 666 667
  const _MaterialInterior({
    Key key,
    @required this.child,
    @required this.shape,
668
    this.borderOnForeground = true,
669
    this.clipBehavior = Clip.none,
670 671 672
    @required this.elevation,
    @required this.color,
    @required this.shadowColor,
673
    Curve curve = Curves.linear,
674 675 676
    @required Duration duration,
  }) : assert(child != null),
       assert(shape != null),
677
       assert(clipBehavior != null),
678
       assert(elevation != null && elevation >= 0.0),
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
       assert(color != null),
       assert(shadowColor != null),
       super(key: key, curve: curve, duration: duration);

  /// The widget below this widget in the tree.
  ///
  /// {@macro flutter.widgets.child}
  final Widget child;

  /// The border of the widget.
  ///
  /// This border will be painted, and in addition the outer path of the border
  /// determines the physical shape.
  final ShapeBorder shape;

694 695 696 697 698 699
  /// Whether to paint the border in front of the child.
  ///
  /// The default value is true.
  /// If false, the border will be painted behind the child.
  final bool borderOnForeground;

700
  /// {@macro flutter.widgets.Clip}
701 702
  ///
  /// Defaults to [Clip.none], and must not be null.
703 704
  final Clip clipBehavior;

705 706 707 708
  /// The target z-coordinate at which to place this physical object relative
  /// to its parent.
  ///
  /// The value is non-negative.
709 710 711 712 713 714 715 716 717
  final double elevation;

  /// The target background color.
  final Color color;

  /// The target shadow color.
  final Color shadowColor;

  @override
718
  _MaterialInteriorState createState() => _MaterialInteriorState();
719 720 721 722

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
    super.debugFillProperties(description);
723 724
    description.add(DiagnosticsProperty<ShapeBorder>('shape', shape));
    description.add(DoubleProperty('elevation', elevation));
725 726
    description.add(ColorProperty('color', color));
    description.add(ColorProperty('shadowColor', shadowColor));
727 728 729 730 731 732 733 734 735 736
  }
}

class _MaterialInteriorState extends AnimatedWidgetBaseState<_MaterialInterior> {
  Tween<double> _elevation;
  ColorTween _shadowColor;
  ShapeBorderTween _border;

  @override
  void forEachTween(TweenVisitor<dynamic> visitor) {
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    _elevation = visitor(
      _elevation,
      widget.elevation,
      (dynamic value) => Tween<double>(begin: value as double),
    ) as Tween<double>;
    _shadowColor = visitor(
      _shadowColor,
      widget.shadowColor,
      (dynamic value) => ColorTween(begin: value as Color),
    ) as ColorTween;
    _border = visitor(
      _border,
      widget.shape,
      (dynamic value) => ShapeBorderTween(begin: value as ShapeBorder),
    ) as ShapeBorderTween;
752 753 754 755
  }

  @override
  Widget build(BuildContext context) {
756
    final ShapeBorder shape = _border.evaluate(animation);
757
    final double elevation = _elevation.evaluate(animation);
758 759
    return PhysicalShape(
      child: _ShapeBorderPaint(
760 761
        child: widget.child,
        shape: shape,
762
        borderOnForeground: widget.borderOnForeground,
763
      ),
764
      clipper: ShapeBorderClipper(
765
        shape: shape,
766
        textDirection: Directionality.of(context),
767
      ),
768
      clipBehavior: widget.clipBehavior,
769
      elevation: elevation,
770
      color: ElevationOverlay.applyOverlay(context, widget.color, elevation),
771 772 773 774
      shadowColor: _shadowColor.evaluate(animation),
    );
  }
}
775 776 777 778 779

class _ShapeBorderPaint extends StatelessWidget {
  const _ShapeBorderPaint({
    @required this.child,
    @required this.shape,
780
    this.borderOnForeground = true,
781 782 783 784
  });

  final Widget child;
  final ShapeBorder shape;
785
  final bool borderOnForeground;
786 787 788

  @override
  Widget build(BuildContext context) {
789
    return CustomPaint(
790
      child: child,
791 792
      painter: borderOnForeground ? null : _ShapeBorderPainter(shape, Directionality.of(context)),
      foregroundPainter: borderOnForeground ? _ShapeBorderPainter(shape, Directionality.of(context)) : null,
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    );
  }
}

class _ShapeBorderPainter extends CustomPainter {
  _ShapeBorderPainter(this.border, this.textDirection);
  final ShapeBorder border;
  final TextDirection textDirection;

  @override
  void paint(Canvas canvas, Size size) {
    border.paint(canvas, Offset.zero & size, textDirection: textDirection);
  }

  @override
  bool shouldRepaint(_ShapeBorderPainter oldDelegate) {
    return oldDelegate.border != border;
  }
}