material.dart 28.4 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 6
// @dart = 2.8

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/widgets.dart';
10

11
import 'constants.dart';
12
import 'elevation_overlay.dart';
13
import 'theme.dart';
14

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

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

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

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

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

  /// A transparent piece of material that draws ink splashes and highlights.
41 42 43 44 45 46 47 48 49
  ///
  /// 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.
50
  transparency
51 52
}

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

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

74
  /// The ticker provider used by the controller.
75
  ///
76 77 78 79 80
  /// 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].
81
  ///
82
  /// The ink feature will paint as part of this controller.
83
  void addInkFeature(InkFeature feature);
84 85 86

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

89 90
/// A piece of material.
///
91 92
/// The Material widget is responsible for:
///
93 94 95
/// 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.
96 97 98 99 100 101 102
/// 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
///
103 104 105
/// 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
106
/// shadows.
107 108 109 110 111 112
///
/// 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].
///
113
/// In general, the features of a [Material] should not change over time (e.g. a
114
/// [Material] should not change its [color], [shadowColor] or [type]).
115 116 117 118
/// 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].
119
///
120 121
/// ## Shape
///
122
/// The shape for material is determined by [shape], [type], and [borderRadius].
123
///
124 125 126 127 128
///  - 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:
129 130 131 132 133 134 135 136
///    - [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.
///
137 138 139 140
/// ## Border
///
/// If [shape] is not null, then its border will also be painted (if any).
///
141
/// ## Layout change notifications
142
///
Ian Hickson's avatar
Ian Hickson committed
143 144 145 146 147 148 149 150
/// 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.
151
///
152 153 154 155 156 157 158 159 160 161
/// ## Painting over the material
///
/// Material widgets will often trigger reactions on their nearest material
/// ancestor. For example, [ListTile.hoverColor] triggers a reaction on the
/// tile's material when a pointer is hovering over it. These reactions will be
/// obscured if any widget in between them and the material paints in such a
/// way as to obscure the material (such as setting a [BoxDecoration.color] on
/// a [DecoratedBox]). To avoid this behavior, use [InkDecoration] to decorate
/// the material itself.
///
162 163
/// See also:
///
164
///  * [MergeableMaterial], a piece of material that can split and re-merge.
165
///  * [Card], a wrapper for a [Material] of [type] [MaterialType.card].
166
///  * <https://material.io/design/>
167
class Material extends StatefulWidget {
168 169
  /// Creates a piece of material.
  ///
170 171 172
  /// The [type], [elevation], [shadowColor], [borderOnForeground],
  /// [clipBehavior], and [animationDuration] arguments must not be null.
  /// Additionally, [elevation] must be non-negative.
173
  ///
174
  /// If a [shape] is specified, then the [borderRadius] property must be
175 176 177 178
  /// 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.
179
  const Material({
180
    Key key,
181 182
    this.type = MaterialType.canvas,
    this.elevation = 0.0,
183
    this.color,
184
    this.shadowColor,
185
    this.textStyle,
186
    this.borderRadius,
187
    this.shape,
188
    this.borderOnForeground = true,
189
    this.clipBehavior = Clip.none,
190
    this.animationDuration = kThemeChangeDuration,
191
    this.child,
192
  }) : assert(type != null),
193
       assert(elevation != null && elevation >= 0.0),
194
       assert(!(shape != null && borderRadius != null)),
195
       assert(animationDuration != null),
196
       assert(!(identical(type, MaterialType.circle) && (borderRadius != null || shape != null))),
197
       assert(borderOnForeground != null),
198
       assert(clipBehavior != null),
199
       super(key: key);
200

201
  /// The widget below this widget in the tree.
202 203
  ///
  /// {@macro flutter.widgets.child}
204
  final Widget child;
205

206 207 208
  /// 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.
209
  final MaterialType type;
210

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

234
  /// The color to paint the material.
235 236 237
  ///
  /// Must be opaque. To create a transparent piece of material, use
  /// [MaterialType.transparency].
238
  ///
239
  /// To support dark themes, if the surrounding
240 241 242
  /// [ThemeData.applyElevationOverlayColor] is true and [ThemeData.brightness]
  /// is [Brightness.dark] then a semi-transparent overlay color will be
  /// composited on top of this color to indicate the elevation.
243
  ///
244
  /// By default, the color is derived from the [type] of material.
245
  final Color color;
246

247 248
  /// The color to paint the shadow below the material.
  ///
249 250 251 252 253 254 255 256 257 258 259
  /// If null, [ThemeData.shadowColor] is used, which defaults to fully opaque black.
  ///
  /// Shadows can be difficult to see in a dark theme, so the elevation of a
  /// surface should be portrayed with an "overlay" in addition to the shadow.
  /// As the elevation of the component increases, the overlay increases in
  /// opacity.
  ///
  /// See also:
  ///
  ///  * [ThemeData.applyElevationOverlayColor], which turns elevation overlay
  /// on or off for dark themes.
260 261
  final Color shadowColor;

262
  /// The typographical style to use for text within this material.
263
  final TextStyle textStyle;
264

265 266 267 268 269 270 271
  /// 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.
272 273
  final ShapeBorder shape;

274 275 276 277 278 279
  /// 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;

280 281 282 283 284 285
  /// {@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}
286 287
  ///
  /// Defaults to [Clip.none], and must not be null.
288 289
  final Clip clipBehavior;

290
  /// Defines the duration of animated changes for [shape], [elevation],
291
  /// [shadowColor] and the elevation overlay if it is applied.
292 293 294 295
  ///
  /// The default value is [kThemeChangeDuration].
  final Duration animationDuration;

296 297 298
  /// If non-null, the corners of this box are rounded by this
  /// [BorderRadiusGeometry] value.
  ///
299 300 301
  /// Otherwise, the corners specified for the current [type] of material are
  /// used.
  ///
302 303
  /// If [shape] is non null then the border radius is ignored.
  ///
304
  /// Must be null if [type] is [MaterialType.circle].
305
  final BorderRadiusGeometry borderRadius;
306

307 308
  /// The ink controller from the closest instance of this class that
  /// encloses the given context.
309 310 311 312 313 314
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// MaterialInkController inkController = Material.of(context);
  /// ```
315
  static MaterialInkController of(BuildContext context) {
316
    final _RenderInkFeatures result = context.findAncestorRenderObjectOfType<_RenderInkFeatures>();
317 318 319
    return result;
  }

320
  @override
321
  _MaterialState createState() => _MaterialState();
322

323
  @override
324 325
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
326 327
    properties.add(EnumProperty<MaterialType>('type', type));
    properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0));
328
    properties.add(ColorProperty('color', color, defaultValue: null));
329
    properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null));
330
    textStyle?.debugFillProperties(properties, prefix: 'textStyle.');
331
    properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
332
    properties.add(DiagnosticsProperty<bool>('borderOnForeground', borderOnForeground, defaultValue: true));
333
    properties.add(DiagnosticsProperty<BorderRadiusGeometry>('borderRadius', borderRadius, defaultValue: null));
334
  }
335 336 337

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

340
class _MaterialState extends State<Material> with TickerProviderStateMixin {
341
  final GlobalKey _inkFeatureRenderer = GlobalKey(debugLabel: 'ink renderer');
342

343
  Color _getBackgroundColor(BuildContext context) {
344 345 346 347 348 349 350 351 352 353 354 355 356
    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;
      }
357
    }
358
    return color;
359 360
  }

361
  @override
362
  Widget build(BuildContext context) {
363
    final Color backgroundColor = _getBackgroundColor(context);
364 365 366 367 368 369 370
    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)'
    );
371
    Widget contents = widget.child;
372
    if (contents != null) {
373
      contents = AnimatedDefaultTextStyle(
374
        style: widget.textStyle ?? Theme.of(context).textTheme.bodyText2,
375
        duration: widget.animationDuration,
376
        child: contents,
377 378
      );
    }
379
    contents = NotificationListener<LayoutChangedNotification>(
380
      onNotification: (LayoutChangedNotification notification) {
381
        final _RenderInkFeatures renderer = _inkFeatureRenderer.currentContext.findRenderObject() as _RenderInkFeatures;
382
        renderer._didChangeLayout();
383
        return false;
384
      },
385
      child: _InkFeatures(
386
        key: _inkFeatureRenderer,
387
        absorbHitTest: widget.type != MaterialType.transparency,
388
        color: backgroundColor,
389 390
        child: contents,
        vsync: this,
391
      ),
392
    );
393

Josh Soref's avatar
Josh Soref committed
394
    // PhysicalModel has a temporary workaround for a performance issue that
395 396
    // 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
397
    // Until the saveLayer performance issue is resolved, we're keeping this
398 399
    // 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
400
    // specified rectangles (e.g shape RoundedRectangleBorder with radius 0, but
401 402 403
    // 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) {
404
      return AnimatedPhysicalModel(
405
        curve: Curves.fastOutSlowIn,
406
        duration: widget.animationDuration,
407
        shape: BoxShape.rectangle,
408
        clipBehavior: widget.clipBehavior,
409 410
        borderRadius: BorderRadius.zero,
        elevation: widget.elevation,
411
        color: ElevationOverlay.applyOverlay(context, backgroundColor, widget.elevation),
412
        shadowColor: widget.shadowColor ?? Theme.of(context).shadowColor,
413 414 415 416 417
        animateColor: false,
        child: contents,
      );
    }

418 419
    final ShapeBorder shape = _getShape();

420 421 422 423 424 425 426 427
    if (widget.type == MaterialType.transparency) {
      return _transparentInterior(
        context: context,
        shape: shape,
        clipBehavior: widget.clipBehavior,
        contents: contents,
      );
    }
428

429
    return _MaterialInterior(
430
      curve: Curves.fastOutSlowIn,
431
      duration: widget.animationDuration,
432
      shape: shape,
433
      borderOnForeground: widget.borderOnForeground,
434
      clipBehavior: widget.clipBehavior,
435 436
      elevation: widget.elevation,
      color: backgroundColor,
437
      shadowColor: widget.shadowColor ?? Theme.of(context).shadowColor,
438 439 440 441
      child: contents,
    );
  }

442 443 444 445 446 447
  static Widget _transparentInterior({
    @required BuildContext context,
    @required ShapeBorder shape,
    @required Clip clipBehavior,
    @required Widget contents,
  }) {
448
    final _ShapeBorderPaint child = _ShapeBorderPaint(
449 450 451 452 453 454
      child: contents,
      shape: shape,
    );
    if (clipBehavior == Clip.none) {
      return child;
    }
455
    return ClipPath(
456
      child: child,
457 458 459 460
      clipper: ShapeBorderClipper(
        shape: shape,
        textDirection: Directionality.of(context),
      ),
461
      clipBehavior: clipBehavior,
462 463 464 465 466 467 468 469 470 471 472 473 474 475
    );
  }

  // 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)
476
      return RoundedRectangleBorder(borderRadius: widget.borderRadius);
477 478 479
    switch (widget.type) {
      case MaterialType.canvas:
      case MaterialType.transparency:
480
        return const RoundedRectangleBorder();
481 482 483

      case MaterialType.card:
      case MaterialType.button:
484
        return RoundedRectangleBorder(
485
          borderRadius: widget.borderRadius ?? kMaterialEdges[widget.type],
486
        );
487

488 489 490
      case MaterialType.circle:
        return const CircleBorder();
    }
491
    return const RoundedRectangleBorder();
492 493 494
  }
}

495
class _RenderInkFeatures extends RenderProxyBox implements MaterialInkController {
496 497 498
  _RenderInkFeatures({
    RenderBox child,
    @required this.vsync,
499
    this.absorbHitTest,
500 501 502
    this.color,
  }) : assert(vsync != null),
       super(child);
503 504 505 506

  // 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.
507
  @override
508
  final TickerProvider vsync;
509 510 511 512

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

516 517
  bool absorbHitTest;

518
  List<InkFeature> _inkFeatures;
519

520
  @override
521 522
  void addInkFeature(InkFeature feature) {
    assert(!feature._debugDisposed);
523
    assert(feature._controller == this);
524
    _inkFeatures ??= <InkFeature>[];
525 526 527 528 529 530
    assert(!_inkFeatures.contains(feature));
    _inkFeatures.add(feature);
    markNeedsPaint();
  }

  void _removeFeature(InkFeature feature) {
531
    assert(_inkFeatures != null);
532 533 534 535
    _inkFeatures.remove(feature);
    markNeedsPaint();
  }

536
  void _didChangeLayout() {
537
    if (_inkFeatures != null && _inkFeatures.isNotEmpty)
538 539 540
      markNeedsPaint();
  }

541
  @override
542
  bool hitTestSelf(Offset position) => absorbHitTest;
543

544
  @override
545
  void paint(PaintingContext context, Offset offset) {
546
    if (_inkFeatures != null && _inkFeatures.isNotEmpty) {
547 548 549
      final Canvas canvas = context.canvas;
      canvas.save();
      canvas.translate(offset.dx, offset.dy);
550
      canvas.clipRect(Offset.zero & size);
551
      for (final InkFeature inkFeature in _inkFeatures)
552 553 554 555 556 557 558
        inkFeature._paint(canvas);
      canvas.restore();
    }
    super.paint(context, offset);
  }
}

559
class _InkFeatures extends SingleChildRenderObjectWidget {
560 561 562 563
  const _InkFeatures({
    Key key,
    this.color,
    @required this.vsync,
564
    @required this.absorbHitTest,
565 566
    Widget child,
  }) : super(key: key, child: child);
567 568 569

  // 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.
570 571 572

  final Color color;

573 574
  final TickerProvider vsync;

575 576
  final bool absorbHitTest;

577
  @override
578
  _RenderInkFeatures createRenderObject(BuildContext context) {
579
    return _RenderInkFeatures(
580
      color: color,
581
      absorbHitTest: absorbHitTest,
582
      vsync: vsync,
583 584
    );
  }
585

586
  @override
587
  void updateRenderObject(BuildContext context, _RenderInkFeatures renderObject) {
588 589
    renderObject..color = color
                ..absorbHitTest = absorbHitTest;
590
    assert(vsync == renderObject.vsync);
591 592 593
  }
}

594 595
/// A visual reaction on a piece of [Material].
///
596 597 598
/// To add an ink feature to a piece of [Material], obtain the
/// [MaterialInkController] via [Material.of] and call
/// [MaterialInkController.addInkFeature].
599
abstract class InkFeature {
600
  /// Initializes fields for subclasses.
601
  InkFeature({
602 603
    @required MaterialInkController controller,
    @required this.referenceBox,
604
    this.onRemoved,
605 606
  }) : assert(controller != null),
       assert(referenceBox != null),
607
       _controller = controller as _RenderInkFeatures;
608

609 610 611 612
  /// The [MaterialInkController] associated with this [InkFeature].
  ///
  /// Typically used by subclasses to call
  /// [MaterialInkController.markNeedsPaint] when they need to repaint.
613
  MaterialInkController get controller => _controller;
614
  final _RenderInkFeatures _controller;
615 616

  /// The render box whose visual position defines the frame of reference for this ink feature.
617
  final RenderBox referenceBox;
618 619

  /// Called when the ink feature is no longer visible on the material.
620 621 622 623
  final VoidCallback onRemoved;

  bool _debugDisposed = false;

624
  /// Free up the resources associated with this ink feature.
625
  @mustCallSuper
626 627
  void dispose() {
    assert(!_debugDisposed);
628 629 630 631
    assert(() {
      _debugDisposed = true;
      return true;
    }());
632
    _controller._removeFeature(this);
633 634 635 636 637 638 639 640
    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
641 642
    final List<RenderObject> descendants = <RenderObject>[referenceBox];
    RenderObject node = referenceBox;
643
    while (node != _controller) {
644
      node = node.parent as RenderObject;
645
      assert(node != null);
646
      descendants.add(node);
647 648
    }
    // determine the transform that gets our coordinate system to be like theirs
649
    final Matrix4 transform = Matrix4.identity();
650 651 652
    assert(descendants.length >= 2);
    for (int index = descendants.length - 1; index > 0; index -= 1)
      descendants[index].applyPaintTransform(descendants[index - 1], transform);
653 654 655
    paintFeature(canvas, transform);
  }

656 657 658
  /// Override this method to paint the ink feature.
  ///
  /// The transform argument gives the coordinate conversion from the coordinate
659
  /// system of the canvas to the coordinate system of the [referenceBox].
660
  @protected
661 662
  void paintFeature(Canvas canvas, Matrix4 transform);

663
  @override
664
  String toString() => describeIdentity(this);
665
}
666 667 668 669 670 671 672 673 674

/// 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.
675
  ShapeBorderTween({ShapeBorder begin, ShapeBorder end}) : super(begin: begin, end: end);
676 677 678 679 680 681 682 683 684 685 686 687

  /// 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 {
688 689 690 691 692
  /// 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.
693 694 695 696
  const _MaterialInterior({
    Key key,
    @required this.child,
    @required this.shape,
697
    this.borderOnForeground = true,
698
    this.clipBehavior = Clip.none,
699 700 701
    @required this.elevation,
    @required this.color,
    @required this.shadowColor,
702
    Curve curve = Curves.linear,
703 704 705
    @required Duration duration,
  }) : assert(child != null),
       assert(shape != null),
706
       assert(clipBehavior != null),
707
       assert(elevation != null && elevation >= 0.0),
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
       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;

723 724 725 726 727 728
  /// 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;

729
  /// {@macro flutter.widgets.Clip}
730 731
  ///
  /// Defaults to [Clip.none], and must not be null.
732 733
  final Clip clipBehavior;

734 735 736 737
  /// The target z-coordinate at which to place this physical object relative
  /// to its parent.
  ///
  /// The value is non-negative.
738 739 740 741 742 743 744 745 746
  final double elevation;

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

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

  @override
747
  _MaterialInteriorState createState() => _MaterialInteriorState();
748 749 750 751

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
    super.debugFillProperties(description);
752 753
    description.add(DiagnosticsProperty<ShapeBorder>('shape', shape));
    description.add(DoubleProperty('elevation', elevation));
754 755
    description.add(ColorProperty('color', color));
    description.add(ColorProperty('shadowColor', shadowColor));
756 757 758 759 760 761 762 763 764 765
  }
}

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

  @override
  void forEachTween(TweenVisitor<dynamic> visitor) {
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    _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;
781 782 783 784
  }

  @override
  Widget build(BuildContext context) {
785
    final ShapeBorder shape = _border.evaluate(animation);
786
    final double elevation = _elevation.evaluate(animation);
787 788
    return PhysicalShape(
      child: _ShapeBorderPaint(
789 790
        child: widget.child,
        shape: shape,
791
        borderOnForeground: widget.borderOnForeground,
792
      ),
793
      clipper: ShapeBorderClipper(
794
        shape: shape,
795
        textDirection: Directionality.of(context),
796
      ),
797
      clipBehavior: widget.clipBehavior,
798
      elevation: elevation,
799
      color: ElevationOverlay.applyOverlay(context, widget.color, elevation),
800 801 802 803
      shadowColor: _shadowColor.evaluate(animation),
    );
  }
}
804 805 806 807 808

class _ShapeBorderPaint extends StatelessWidget {
  const _ShapeBorderPaint({
    @required this.child,
    @required this.shape,
809
    this.borderOnForeground = true,
810 811 812 813
  });

  final Widget child;
  final ShapeBorder shape;
814
  final bool borderOnForeground;
815 816 817

  @override
  Widget build(BuildContext context) {
818
    return CustomPaint(
819
      child: child,
820 821
      painter: borderOnForeground ? null : _ShapeBorderPainter(shape, Directionality.of(context)),
      foregroundPainter: borderOnForeground ? _ShapeBorderPainter(shape, Directionality.of(context)) : null,
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    );
  }
}

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