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

5
import 'dart:ui' as ui show Image, ImageFilter;
6

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

11
import 'debug.dart';
12
import 'framework.dart';
13
import 'localizations.dart';
14

15
export 'package:flutter/animation.dart';
16 17
export 'package:flutter/foundation.dart' show
  ChangeNotifier,
18
  FlutterErrorDetails,
19 20 21
  Listenable,
  TargetPlatform,
  ValueNotifier;
22
export 'package:flutter/painting.dart';
23
export 'package:flutter/rendering.dart' show
24 25
  AlignmentTween,
  AlignmentGeometryTween,
26 27 28 29 30
  Axis,
  BoxConstraints,
  CrossAxisAlignment,
  CustomClipper,
  CustomPainter,
31
  CustomPainterSemantics,
32
  DecorationPosition,
33 34 35 36 37
  FlexFit,
  FlowDelegate,
  FlowPaintingContext,
  FractionalOffsetTween,
  HitTestBehavior,
38
  LayerLink,
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  MainAxisAlignment,
  MainAxisSize,
  MultiChildLayoutDelegate,
  Overflow,
  PaintingContext,
  PointerCancelEvent,
  PointerCancelEventListener,
  PointerDownEvent,
  PointerDownEventListener,
  PointerEvent,
  PointerMoveEvent,
  PointerMoveEventListener,
  PointerUpEvent,
  PointerUpEventListener,
  RelativeRect,
54
  SemanticsBuilderCallback,
55
  ShaderCallback,
56
  ShapeBorderClipper,
57
  SingleChildLayoutDelegate,
58
  StackFit,
59 60
  TextOverflow,
  ValueChanged,
Adam Barth's avatar
Adam Barth committed
61 62 63
  ValueGetter,
  WrapAlignment,
  WrapCrossAlignment;
64

65 66 67 68
// Examples can assume:
// class TestWidget extends StatelessWidget { @override Widget build(BuildContext context) => const Placeholder(); }
// WidgetTester tester;

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
// BIDIRECTIONAL TEXT SUPPORT

/// A widget that determines the ambient directionality of text and
/// text-direction-sensitive render objects.
///
/// For example, [Padding] depends on the [Directionality] to resolve
/// [EdgeInsetsDirectional] objects into absolute [EdgeInsets] objects.
class Directionality extends InheritedWidget {
  /// Creates a widget that determines the directionality of text and
  /// text-direction-sensitive render objects.
  ///
  /// The [textDirection] and [child] arguments must not be null.
  const Directionality({
    Key key,
    @required this.textDirection,
    @required Widget child
  }) : assert(textDirection != null),
       assert(child != null),
       super(key: key, child: child);

  /// The text direction for this subtree.
  final TextDirection textDirection;

  /// The text direction from the closest instance of this class that encloses
  /// the given context.
  ///
  /// If there is no [Directionality] ancestor widget in the tree at the given
  /// context, then this will return null.
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// TextDirection textDirection = Directionality.of(context);
  /// ```
  static TextDirection of(BuildContext context) {
    final Directionality widget = context.inheritFromWidgetOfExactType(Directionality);
    return widget?.textDirection;
  }

  @override
109
  bool updateShouldNotify(Directionality oldWidget) => textDirection != oldWidget.textDirection;
110 111

  @override
112 113 114
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<TextDirection>('textDirection', textDirection));
115 116 117 118
  }
}


119 120
// PAINTING NODES

121
/// A widget that makes its child partially transparent.
122 123 124 125
///
/// This class paints its child into an intermediate buffer and then blends the
/// child back into the scene partially transparent.
///
Ian Hickson's avatar
Ian Hickson committed
126 127 128 129
/// For values of opacity other than 0.0 and 1.0, this class is relatively
/// expensive because it requires painting the child into an intermediate
/// buffer. For the value 0.0, the child is simply not painted at all. For the
/// value 1.0, the child is painted immediately without an intermediate buffer.
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
///
/// ## Sample code
///
/// This example shows some [Text] when the `_visible` member field is true, and
/// hides it when it is false:
///
/// ```dart
/// new Opacity(
///   opacity: _visible ? 1.0 : 0.0,
///   child: const Text('Now you see me, now you don\'t!'),
/// )
/// ```
///
/// This is more efficient than adding and removing the child widget from the
/// tree on demand.
///
146 147 148 149 150 151
/// ## Opacity Animation
///
/// Animating an [Opacity] widget directly causes the widget (and possibly its
/// subtree) to rebuild each frame, which is not very efficient. Consider using
/// an [AnimatedOpacity] instead.
///
152 153
/// See also:
///
154 155 156
///  * [Visibility], which can hide a child more efficiently (albeit less
///    subtly, because it is either visible or hidden, rather than allowing
///    fractional opacity values).
157
///  * [ShaderMask], which can apply more elaborate effects to its child.
158 159
///  * [Transform], which applies an arbitrary transform to its child widget at
///    paint time.
160 161 162 163
///  * [AnimatedOpacity], which uses an animation internally to efficiently
///    animate opacity.
///  * [FadeTransition], which uses a provided animation to efficiently animate
///    opacity.
164
class Opacity extends SingleChildRenderObjectWidget {
165 166 167 168
  /// Creates a widget that makes its child partially transparent.
  ///
  /// The [opacity] argument must not be null and must be between 0.0 and 1.0
  /// (inclusive).
169
  const Opacity({
170 171
    Key key,
    @required this.opacity,
172
    this.alwaysIncludeSemantics = false,
173
    Widget child,
174
  }) : assert(opacity != null && opacity >= 0.0 && opacity <= 1.0),
175
       assert(alwaysIncludeSemantics != null),
176
       super(key: key, child: child);
177

178 179 180 181
  /// The fraction to scale the child's alpha value.
  ///
  /// An opacity of 1.0 is fully opaque. An opacity of 0.0 is fully transparent
  /// (i.e., invisible).
Ian Hickson's avatar
Ian Hickson committed
182 183 184 185 186 187
  ///
  /// The opacity must not be null.
  ///
  /// Values 1.0 and 0.0 are painted with a fast path. Other values
  /// require painting the child into an intermediate buffer, which is
  /// expensive.
188 189
  final double opacity;

190 191 192 193 194 195 196 197 198 199
  /// Whether the semantic information of the children is always included.
  ///
  /// Defaults to false.
  ///
  /// When true, regardless of the opacity settings the child semantic
  /// information is exposed as if the widget were fully visible. This is
  /// useful in cases where labels may be hidden during animations that
  /// would otherwise contribute relevant semantics.
  final bool alwaysIncludeSemantics;

200
  @override
201 202 203 204 205 206
  RenderOpacity createRenderObject(BuildContext context) {
    return new RenderOpacity(
      opacity: opacity,
      alwaysIncludeSemantics: alwaysIncludeSemantics,
    );
  }
207

208
  @override
209
  void updateRenderObject(BuildContext context, RenderOpacity renderObject) {
210 211 212
    renderObject
      ..opacity = opacity
      ..alwaysIncludeSemantics = alwaysIncludeSemantics;
213
  }
214

215
  @override
216 217 218
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DoubleProperty('opacity', opacity));
219
    properties.add(new FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics'));
220
  }
221 222
}

223
/// A widget that applies a mask generated by a [Shader] to its child.
224 225
///
/// For example, [ShaderMask] can be used to gradually fade out the edge
226
/// of a child by using a [new ui.Gradient.linear] mask.
227 228 229 230 231 232 233 234 235
///
/// ## Sample code
///
/// This example makes the text look like it is on fire:
///
/// ```dart
/// new ShaderMask(
///   shaderCallback: (Rect bounds) {
///     return new RadialGradient(
236
///       center: Alignment.topLeft,
237 238 239 240 241 242 243 244 245 246 247 248 249 250
///       radius: 1.0,
///       colors: <Color>[Colors.yellow, Colors.deepOrange.shade900],
///       tileMode: TileMode.mirror,
///     ).createShader(bounds);
///   },
///   child: const Text('I’m burning the memories'),
/// )
/// ```
///
/// See also:
///
///  * [Opacity], which can apply a uniform alpha effect to its child.
///  * [CustomPaint], which lets you draw directly on the canvas.
///  * [DecoratedBox], for another approach at decorating child widgets.
251
///  * [BackdropFilter], which applies an image filter to the background.
252
class ShaderMask extends SingleChildRenderObjectWidget {
253 254
  /// Creates a widget that applies a mask generated by a [Shader] to its child.
  ///
255
  /// The [shaderCallback] and [blendMode] arguments must not be null.
256
  const ShaderMask({
Hans Muller's avatar
Hans Muller committed
257
    Key key,
258
    @required this.shaderCallback,
259
    this.blendMode = BlendMode.modulate,
Hans Muller's avatar
Hans Muller committed
260
    Widget child
261 262 263
  }) : assert(shaderCallback != null),
       assert(blendMode != null),
       super(key: key, child: child);
Hans Muller's avatar
Hans Muller committed
264

265
  /// Called to create the [dart:ui.Shader] that generates the mask.
266 267 268
  ///
  /// The shader callback is called with the current size of the child so that
  /// it can customize the shader to the size and location of the child.
269
  ///
270
  /// Typically this will use a [LinearGradient], [RadialGradient], or
271
  /// [SweepGradient] to create the [dart:ui.Shader], though the
272
  /// [dart:ui.ImageShader] class could also be used.
Hans Muller's avatar
Hans Muller committed
273
  final ShaderCallback shaderCallback;
274

275
  /// The [BlendMode] to use when applying the shader to the child.
276
  ///
277 278 279
  /// The default, [BlendMode.modulate], is useful for applying an alpha blend
  /// to the child. Other blend modes can be used to create other effects.
  final BlendMode blendMode;
Hans Muller's avatar
Hans Muller committed
280

281
  @override
282
  RenderShaderMask createRenderObject(BuildContext context) {
Hans Muller's avatar
Hans Muller committed
283 284
    return new RenderShaderMask(
      shaderCallback: shaderCallback,
285
      blendMode: blendMode,
Hans Muller's avatar
Hans Muller committed
286 287 288
    );
  }

289
  @override
290
  void updateRenderObject(BuildContext context, RenderShaderMask renderObject) {
291 292
    renderObject
      ..shaderCallback = shaderCallback
293
      ..blendMode = blendMode;
Hans Muller's avatar
Hans Muller committed
294 295 296
  }
}

297
/// A widget that applies a filter to the existing painted content and then paints [child].
298 299 300
///
/// This effect is relatively expensive, especially if the filter is non-local,
/// such as a blur.
301 302 303 304 305
///
/// See also:
///
///  * [DecoratedBox], which draws a background under (or over) a widget.
///  * [Opacity], which changes the opacity of the widget itself.
306
class BackdropFilter extends SingleChildRenderObjectWidget {
307 308 309
  /// Creates a backdrop filter.
  ///
  /// The [filter] argument must not be null.
310
  const BackdropFilter({
311
    Key key,
312
    @required this.filter,
313
    Widget child
314 315
  }) : assert(filter != null),
       super(key: key, child: child);
316

317 318
  /// The image filter to apply to the existing painted content before painting the child.
  ///
319
  /// For example, consider using [ImageFilter.blur] to create a backdrop
320
  /// blur effect
321 322 323 324 325 326 327 328 329 330 331 332 333
  final ui.ImageFilter filter;

  @override
  RenderBackdropFilter createRenderObject(BuildContext context) {
    return new RenderBackdropFilter(filter: filter);
  }

  @override
  void updateRenderObject(BuildContext context, RenderBackdropFilter renderObject) {
    renderObject.filter = filter;
  }
}

334
/// A widget that provides a canvas on which to draw during the paint phase.
335
///
336
/// When asked to paint, [CustomPaint] first asks its [painter] to paint on the
337
/// current canvas, then it paints its child, and then, after painting its
338
/// child, it asks its [foregroundPainter] to paint. The coordinate system of the
339 340
/// canvas matches the coordinate system of the [CustomPaint] object. The
/// painters are expected to paint within a rectangle starting at the origin and
341
/// encompassing a region of the given size. (If the painters paint outside
342 343
/// those bounds, there might be insufficient memory allocated to rasterize the
/// painting commands and the resulting behavior is undefined.)
344
///
345 346
/// Painters are implemented by subclassing [CustomPainter].
///
Ian Hickson's avatar
Ian Hickson committed
347 348 349 350 351 352
/// Because custom paint calls its painters during paint, you cannot call
/// `setState` or `markNeedsLayout` during the callback (the layout for this
/// frame has already happened).
///
/// Custom painters normally size themselves to their child. If they do not have
/// a child, they attempt to size themselves to the [size], which defaults to
353
/// [Size.zero]. [size] must not be null.
354 355 356
///
/// [isComplex] and [willChange] are hints to the compositor's raster cache
/// and must not be null.
357
///
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
/// ## Sample code
///
/// This example shows how the sample custom painter shown at [CustomPainter]
/// could be used in a [CustomPaint] widget to display a background to some
/// text.
///
/// ```dart
/// new CustomPaint(
///   painter: new Sky(),
///   child: new Center(
///     child: new Text(
///       'Once upon a time...',
///       style: const TextStyle(
///         fontSize: 40.0,
///         fontWeight: FontWeight.w900,
///         color: const Color(0xFFFFFFFF),
///       ),
///     ),
///   ),
377
/// )
378 379
/// ```
///
380 381
/// See also:
///
382 383
///  * [CustomPainter], the class to extend when creating custom painters.
///  * [Canvas], the class that a custom painter uses to paint.
384
class CustomPaint extends SingleChildRenderObjectWidget {
385
  /// Creates a widget that delegates its painting.
386 387 388 389
  const CustomPaint({
    Key key,
    this.painter,
    this.foregroundPainter,
390 391 392
    this.size = Size.zero,
    this.isComplex = false,
    this.willChange = false,
393
    Widget child,
394 395 396 397
  }) : assert(size != null),
       assert(isComplex != null),
       assert(willChange != null),
       super(key: key, child: child);
398

399
  /// The painter that paints before the children.
400
  final CustomPainter painter;
401 402

  /// The painter that paints after the children.
403
  final CustomPainter foregroundPainter;
Adam Barth's avatar
Adam Barth committed
404

Ian Hickson's avatar
Ian Hickson committed
405 406 407 408 409 410 411 412 413
  /// The size that this [CustomPaint] should aim for, given the layout
  /// constraints, if there is no child.
  ///
  /// Defaults to [Size.zero].
  ///
  /// If there's a child, this is ignored, and the size of the child is used
  /// instead.
  final Size size;

414 415 416 417
  /// Whether the painting is complex enough to benefit from caching.
  ///
  /// The compositor contains a raster cache that holds bitmaps of layers in
  /// order to avoid the cost of repeatedly rendering those layers on each
418
  /// frame. If this flag is not set, then the compositor will apply its own
419 420 421 422 423 424 425 426
  /// heuristics to decide whether the this layer is complex enough to benefit
  /// from caching.
  final bool isComplex;

  /// Whether the raster cache should be told that this painting is likely
  /// to change in the next frame.
  final bool willChange;

427
  @override
428 429 430 431 432
  RenderCustomPaint createRenderObject(BuildContext context) {
    return new RenderCustomPaint(
      painter: painter,
      foregroundPainter: foregroundPainter,
      preferredSize: size,
433 434
      isComplex: isComplex,
      willChange: willChange,
435 436
    );
  }
437

438
  @override
439
  void updateRenderObject(BuildContext context, RenderCustomPaint renderObject) {
440 441
    renderObject
      ..painter = painter
Ian Hickson's avatar
Ian Hickson committed
442
      ..foregroundPainter = foregroundPainter
443 444 445
      ..preferredSize = size
      ..isComplex = isComplex
      ..willChange = willChange;
446 447
  }

448
  @override
449
  void didUnmountRenderObject(RenderCustomPaint renderObject) {
450 451 452
    renderObject
      ..painter = null
      ..foregroundPainter = null;
453 454 455
  }
}

456
/// A widget that clips its child using a rectangle.
457
///
458
/// By default, [ClipRect] prevents its child from painting outside its
459 460
/// bounds, but the size and location of the clip rect can be customized using a
/// custom [clipper].
461 462
///
/// [ClipRect] is commonly used with these widgets, which commonly paint outside
463
/// their bounds:
464 465 466 467 468 469 470 471 472
///
///  * [CustomPaint]
///  * [CustomSingleChildLayout]
///  * [CustomMultiChildLayout]
///  * [Align] and [Center] (e.g., if [Align.widthFactor] or
///    [Align.heightFactor] is less than 1.0).
///  * [OverflowBox]
///  * [SizedOverflowBox]
///
473
/// ## Sample code
474
///
475 476
/// For example, by combining a [ClipRect] with an [Align], one can show just
/// the top half of an [Image]:
477 478 479 480
///
/// ```dart
/// new ClipRect(
///   child: new Align(
481
///     alignment: Alignment.topCenter,
482
///     heightFactor: 0.5,
483
///     child: new Image.network(userAvatarUrl),
484
///   ),
485
/// )
486 487 488 489 490 491 492 493
/// ```
///
/// See also:
///
///  * [CustomClipper], for information about creating custom clips.
///  * [ClipRRect], for a clip with rounded corners.
///  * [ClipOval], for an elliptical clip.
///  * [ClipPath], for an arbitrarily shaped clip.
494
class ClipRect extends SingleChildRenderObjectWidget {
495 496 497 498
  /// Creates a rectangular clip.
  ///
  /// If [clipper] is null, the clip will match the layout size and position of
  /// the child.
499
  const ClipRect({ Key key, this.clipper, this.clipBehavior = Clip.antiAlias, Widget child }) : super(key: key, child: child);
500

501
  /// If non-null, determines which clip to use.
502 503
  final CustomClipper<Rect> clipper;

504 505 506
  /// {@macro flutter.widget.clipper.clipBehavior}
  final Clip clipBehavior;

507
  @override
508
  RenderClipRect createRenderObject(BuildContext context) => new RenderClipRect(clipper: clipper, clipBehavior: clipBehavior);
509

510
  @override
511
  void updateRenderObject(BuildContext context, RenderClipRect renderObject) {
512 513 514
    renderObject.clipper = clipper;
  }

515
  @override
516 517 518
  void didUnmountRenderObject(RenderClipRect renderObject) {
    renderObject.clipper = null;
  }
519 520

  @override
521 522 523
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null));
524
  }
525 526
}

527
/// A widget that clips its child using a rounded rectangle.
528
///
529 530 531
/// By default, [ClipRRect] uses its own bounds as the base rectangle for the
/// clip, but the size and location of the clip can be customized using a custom
/// [clipper].
532 533 534 535 536 537 538
///
/// See also:
///
///  * [CustomClipper], for information about creating custom clips.
///  * [ClipRect], for more efficient clips without rounded corners.
///  * [ClipOval], for an elliptical clip.
///  * [ClipPath], for an arbitrarily shaped clip.
539
class ClipRRect extends SingleChildRenderObjectWidget {
540
  /// Creates a rounded-rectangular clip.
541 542 543 544 545
  ///
  /// The [borderRadius] defaults to [BorderRadius.zero], i.e. a rectangle with
  /// right-angled corners.
  ///
  /// If [clipper] is non-null, then [borderRadius] is ignored.
546
  const ClipRRect({
547
    Key key,
548 549
    this.borderRadius,
    this.clipper,
550
    this.clipBehavior = Clip.antiAlias,
551
    Widget child,
552
  }) : assert(borderRadius != null || clipper != null),
553
       assert(clipBehavior != null),
554
       super(key: key, child: child);
555

556
  /// The border radius of the rounded corners.
557
  ///
558 559 560 561
  /// Values are clamped so that horizontal and vertical radii sums do not
  /// exceed width/height.
  ///
  /// This value is ignored if [clipper] is non-null.
562
  final BorderRadius borderRadius;
563

564 565 566
  /// If non-null, determines which clip to use.
  final CustomClipper<RRect> clipper;

567 568 569
  /// {@macro flutter.widget.clipper.clipBehavior}
  final Clip clipBehavior;

570
  @override
571
  RenderClipRRect createRenderObject(BuildContext context) => new RenderClipRRect(borderRadius: borderRadius, clipper: clipper, clipBehavior: clipBehavior);
572

573
  @override
574
  void updateRenderObject(BuildContext context, RenderClipRRect renderObject) {
575
    renderObject
576 577
      ..borderRadius = borderRadius
      ..clipper = clipper;
578
  }
579 580

  @override
581 582 583 584
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<BorderRadius>('borderRadius', borderRadius, showName: false, defaultValue: null));
    properties.add(new DiagnosticsProperty<CustomClipper<RRect>>('clipper', clipper, defaultValue: null));
585
  }
586 587
}

588
/// A widget that clips its child using an oval.
589
///
590 591 592
/// By default, inscribes an axis-aligned oval into its layout dimensions and
/// prevents its child from painting outside that oval, but the size and
/// location of the clip oval can be customized using a custom [clipper].
593 594 595 596 597 598 599 600
/// See also:
///
/// See also:
///
///  * [CustomClipper], for information about creating custom clips.
///  * [ClipRect], for more efficient clips without rounded corners.
///  * [ClipRRect], for a clip with rounded corners.
///  * [ClipPath], for an arbitrarily shaped clip.
601
class ClipOval extends SingleChildRenderObjectWidget {
602 603 604 605
  /// Creates an oval-shaped clip.
  ///
  /// If [clipper] is null, the oval will be inscribed into the layout size and
  /// position of the child.
606
  const ClipOval({ Key key, this.clipper, this.clipBehavior = Clip.antiAlias, Widget child }) : super(key: key, child: child);
607

608
  /// If non-null, determines which clip to use.
Ian Hickson's avatar
Ian Hickson committed
609 610 611 612 613 614 615 616
  ///
  /// The delegate returns a rectangle that describes the axis-aligned
  /// bounding box of the oval. The oval's axes will themselves also
  /// be axis-aligned.
  ///
  /// If the [clipper] delegate is null, then the oval uses the
  /// widget's bounding box (the layout dimensions of the render
  /// object) instead.
617 618
  final CustomClipper<Rect> clipper;

619 620 621
  /// {@macro flutter.widget.clipper.clipBehavior}
  final Clip clipBehavior;

622
  @override
623
  RenderClipOval createRenderObject(BuildContext context) => new RenderClipOval(clipper: clipper, clipBehavior: clipBehavior);
624

625
  @override
626
  void updateRenderObject(BuildContext context, RenderClipOval renderObject) {
627 628 629
    renderObject.clipper = clipper;
  }

630
  @override
631 632 633
  void didUnmountRenderObject(RenderClipOval renderObject) {
    renderObject.clipper = null;
  }
634 635

  @override
636 637 638
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null));
639
  }
640 641
}

642
/// A widget that clips its child using a path.
Ian Hickson's avatar
Ian Hickson committed
643
///
644
/// Calls a callback on a delegate whenever the widget is to be
Ian Hickson's avatar
Ian Hickson committed
645 646 647 648 649 650 651 652 653 654
/// painted. The callback returns a path and the widget prevents the
/// child from painting outside the path.
///
/// Clipping to a path is expensive. Certain shapes have more
/// optimized widgets:
///
///  * To clip to a rectangle, consider [ClipRect].
///  * To clip to an oval or circle, consider [ClipOval].
///  * To clip to a rounded rectangle, consider [ClipRRect].
class ClipPath extends SingleChildRenderObjectWidget {
655 656 657 658 659 660
  /// Creates a path clip.
  ///
  /// If [clipper] is null, the clip will be a rectangle that matches the layout
  /// size and location of the child. However, rather than use this default,
  /// consider using a [ClipRect], which can achieve the same effect more
  /// efficiently.
661
  const ClipPath({ Key key, this.clipper, this.clipBehavior = Clip.antiAlias, Widget child }) : super(key: key, child: child);
Ian Hickson's avatar
Ian Hickson committed
662 663 664 665 666 667 668 669

  /// If non-null, determines which clip to use.
  ///
  /// The default clip, which is used if this property is null, is the
  /// bounding box rectangle of the widget. [ClipRect] is a more
  /// efficient way of obtaining that effect.
  final CustomClipper<Path> clipper;

670 671 672
  /// {@macro flutter.widget.clipper.clipBehavior}
  final Clip clipBehavior;

Ian Hickson's avatar
Ian Hickson committed
673
  @override
674
  RenderClipPath createRenderObject(BuildContext context) => new RenderClipPath(clipper: clipper, clipBehavior: clipBehavior);
Ian Hickson's avatar
Ian Hickson committed
675 676 677 678 679 680 681 682 683 684

  @override
  void updateRenderObject(BuildContext context, RenderClipPath renderObject) {
    renderObject.clipper = clipper;
  }

  @override
  void didUnmountRenderObject(RenderClipPath renderObject) {
    renderObject.clipper = null;
  }
685 686

  @override
687 688 689
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<CustomClipper<Path>>('clipper', clipper, defaultValue: null));
690
  }
Ian Hickson's avatar
Ian Hickson committed
691 692
}

693
/// A widget representing a physical layer that clips its children to a shape.
694 695 696
///
/// Physical layers cast shadows based on an [elevation] which is nominally in
/// logical pixels, coming vertically out of the rendering surface.
697
///
698 699 700
/// For shapes that cannot be expressed as a rectangle with rounded corners use
/// [PhysicalShape].
///
701 702 703 704
/// See also:
///
///  * [DecoratedBox], which can apply more arbitrary shadow effects.
///  * [ClipRect], which applies a clip to its child.
705 706
class PhysicalModel extends SingleChildRenderObjectWidget {
  /// Creates a physical model with a rounded-rectangular clip.
707 708 709
  ///
  /// The [color] is required; physical things have a color.
  ///
710
  /// The [shape], [elevation], [color], and [shadowColor] must not be null.
711
  const PhysicalModel({
712
    Key key,
713
    this.shape = BoxShape.rectangle,
714
    this.clipBehavior = Clip.none,
715
    this.borderRadius,
716
    this.elevation = 0.0,
717
    @required this.color,
718
    this.shadowColor = const Color(0xFF000000),
719
    Widget child,
720 721 722
  }) : assert(shape != null),
       assert(elevation != null),
       assert(color != null),
723
       assert(shadowColor != null),
724
       super(key: key, child: child);
725 726 727 728

  /// The type of shape.
  final BoxShape shape;

729 730 731
  /// {@macro flutter.widgets.Clip}
  final Clip clipBehavior;

732 733 734 735
  /// The border radius of the rounded corners.
  ///
  /// Values are clamped so that horizontal and vertical radii sums do not
  /// exceed width/height.
736 737
  ///
  /// This is ignored if the [shape] is not [BoxShape.rectangle].
738 739 740
  final BorderRadius borderRadius;

  /// The z-coordinate at which to place this physical object.
741
  final double elevation;
742 743 744 745

  /// The background color.
  final Color color;

746 747 748
  /// The shadow color.
  final Color shadowColor;

749
  @override
750 751 752
  RenderPhysicalModel createRenderObject(BuildContext context) {
    return new RenderPhysicalModel(
      shape: shape,
753
      clipBehavior: clipBehavior,
754 755 756 757 758
      borderRadius: borderRadius,
      elevation: elevation, color: color,
      shadowColor: shadowColor,
    );
  }
759 760 761 762 763 764 765

  @override
  void updateRenderObject(BuildContext context, RenderPhysicalModel renderObject) {
    renderObject
      ..shape = shape
      ..borderRadius = borderRadius
      ..elevation = elevation
766 767
      ..color = color
      ..shadowColor = shadowColor;
768
  }
769 770

  @override
771 772 773 774 775 776 777
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<BoxShape>('shape', shape));
    properties.add(new DiagnosticsProperty<BorderRadius>('borderRadius', borderRadius));
    properties.add(new DoubleProperty('elevation', elevation));
    properties.add(new DiagnosticsProperty<Color>('color', color));
    properties.add(new DiagnosticsProperty<Color>('shadowColor', shadowColor));
778
  }
779
}
780

781 782 783 784 785 786 787
/// A widget representing a physical layer that clips its children to a path.
///
/// Physical layers cast shadows based on an [elevation] which is nominally in
/// logical pixels, coming vertically out of the rendering surface.
///
/// [PhysicalModel] does the same but only supports shapes that can be expressed
/// as rectangles with rounded corners.
788 789 790 791 792
///
/// See also:
///
///  * [ShapeBorderClipper], which converts a [ShapeBorder] to a [CustomerClipper], as
///    needed by this widget.
793 794 795 796 797 798 799 800 801
class PhysicalShape extends SingleChildRenderObjectWidget {
  /// Creates a physical model with an arbitrary shape clip.
  ///
  /// The [color] is required; physical things have a color.
  ///
  /// The [clipper], [elevation], [color], and [shadowColor] must not be null.
  const PhysicalShape({
    Key key,
    @required this.clipper,
802
    this.clipBehavior = Clip.none,
803
    this.elevation = 0.0,
804
    @required this.color,
805
    this.shadowColor = const Color(0xFF000000),
806 807
    Widget child,
  }) : assert(clipper != null),
808
       assert(clipBehavior != null),
809 810 811 812 813 814
       assert(elevation != null),
       assert(color != null),
       assert(shadowColor != null),
       super(key: key, child: child);

  /// Determines which clip to use.
815 816 817 818
  ///
  /// If the path in question is expressed as a [ShapeBorder] subclass,
  /// consider using the [ShapeBorderClipper] delegate class to adapt the
  /// shape for use with this widget.
819 820
  final CustomClipper<Path> clipper;

821 822 823
  /// {@macro flutter.widgets.Clip}
  final Clip clipBehavior;

824 825 826 827 828 829 830 831 832 833 834 835 836
  /// The z-coordinate at which to place this physical object.
  final double elevation;

  /// The background color.
  final Color color;

  /// When elevation is non zero the color to use for the shadow color.
  final Color shadowColor;

  @override
  RenderPhysicalShape createRenderObject(BuildContext context) {
    return new RenderPhysicalShape(
      clipper: clipper,
837
      clipBehavior: clipBehavior,
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
      elevation: elevation,
      color: color,
      shadowColor: shadowColor
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderPhysicalShape renderObject) {
    renderObject
      ..clipper = clipper
      ..elevation = elevation
      ..color = color
      ..shadowColor = shadowColor;
  }

  @override
854 855 856 857 858 859
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<CustomClipper<Path>>('clipper', clipper));
    properties.add(new DoubleProperty('elevation', elevation));
    properties.add(new DiagnosticsProperty<Color>('color', color));
    properties.add(new DiagnosticsProperty<Color>('shadowColor', shadowColor));
860 861 862
  }
}

863 864
// POSITIONING AND SIZING NODES

865
/// A widget that applies a transformation before painting its child.
866 867 868 869 870 871 872 873 874 875
///
/// ## Sample code
///
/// This example rotates and skews an orange box containing text, keeping the
/// top right corner pinned to its original position.
///
/// ```dart
/// new Container(
///   color: Colors.black,
///   child: new Transform(
876
///     alignment: Alignment.topRight,
877
///     transform: new Matrix4.skewY(0.3)..rotateZ(-math.pi / 12.0),
878 879 880 881 882 883 884 885 886 887
///     child: new Container(
///       padding: const EdgeInsets.all(8.0),
///       color: const Color(0xFFE8581C),
///       child: const Text('Apartment for rent!'),
///     ),
///   ),
/// )
/// ```
///
/// See also:
888
///
889 890
///  * [RotatedBox], which rotates the child widget during layout, not just
///    during painting.
891 892
///  * [FractionalTranslation], which applies a translation to the child
///    that is relative to the child's size.
893 894
///  * [FittedBox], which sizes and positions its child widget to fit the parent
///    according to a given [BoxFit] discipline.
895
class Transform extends SingleChildRenderObjectWidget {
896 897 898
  /// Creates a widget that transforms its child.
  ///
  /// The [transform] argument must not be null.
899
  const Transform({
900
    Key key,
901
    @required this.transform,
902 903
    this.origin,
    this.alignment,
904
    this.transformHitTests = true,
905
    Widget child,
906 907
  }) : assert(transform != null),
       super(key: key, child: child);
908

909 910 911 912 913 914 915 916 917 918 919 920 921
  /// Creates a widget that transforms its child using a rotation around the
  /// center.
  ///
  /// The `angle` argument must not be null. It gives the rotation in clockwise
  /// radians.
  ///
  /// ## Sample code
  ///
  /// This example rotates an orange box containing text around its center by
  /// fifteen degrees.
  ///
  /// ```dart
  /// new Transform.rotate(
922
  ///   angle: -math.pi / 12.0,
923 924 925 926 927 928 929 930 931 932 933
  ///   child: new Container(
  ///     padding: const EdgeInsets.all(8.0),
  ///     color: const Color(0xFFE8581C),
  ///     child: const Text('Apartment for rent!'),
  ///   ),
  /// )
  /// ```
  Transform.rotate({
    Key key,
    @required double angle,
    this.origin,
934 935
    this.alignment = Alignment.center,
    this.transformHitTests = true,
936 937 938 939
    Widget child,
  }) : transform = new Matrix4.rotationZ(angle),
       super(key: key, child: child);

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
  /// Creates a widget that transforms its child using a translation.
  ///
  /// The `offset` argument must not be null. It specifies the translation.
  ///
  /// ## Sample code
  ///
  /// This example shifts the silver-colored child down by fifteen pixels.
  ///
  /// ```dart
  /// new Transform.translate(
  ///   offset: const Offset(0.0, 15.0),
  ///   child: new Container(
  ///     padding: const EdgeInsets.all(8.0),
  ///     color: const Color(0xFF7F7F7F),
  ///     child: const Text('Quarter'),
  ///   ),
  /// )
  /// ```
  Transform.translate({
    Key key,
    @required Offset offset,
961
    this.transformHitTests = true,
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    Widget child,
  }) : transform = new Matrix4.translationValues(offset.dx, offset.dy, 0.0),
       origin = null,
       alignment = null,
       super(key: key, child: child);

  /// Creates a widget that scales its child uniformly.
  ///
  /// The `scale` argument must not be null. It gives the scalar by which
  /// to multiply the `x` and `y` axes.
  ///
  /// The [alignment] controls the origin of the scale; by default, this is
  /// the center of the box.
  ///
  /// ## Sample code
  ///
  /// This example shrinks an orange box containing text such that each dimension
  /// is half the size it would otherwise be.
  ///
  /// ```dart
  /// new Transform.scale(
  ///   scale: 0.5,
  ///   child: new Container(
  ///     padding: const EdgeInsets.all(8.0),
  ///     color: const Color(0xFFE8581C),
  ///     child: const Text('Bad Ideas'),
  ///   ),
  /// )
  /// ```
  Transform.scale({
    Key key,
    @required double scale,
    this.origin,
995 996
    this.alignment = Alignment.center,
    this.transformHitTests = true,
997 998 999 1000
    Widget child,
  }) : transform = new Matrix4.diagonal3Values(scale, scale, 1.0),
       super(key: key, child: child);

1001
  /// The matrix to transform the child by during painting.
1002
  final Matrix4 transform;
1003 1004 1005 1006 1007 1008

  /// The origin of the coordinate system (relative to the upper left corder of
  /// this render object) in which to apply the matrix.
  ///
  /// Setting an origin is equivalent to conjugating the transform matrix by a
  /// translation. This property is provided just for convenience.
1009
  final Offset origin;
1010 1011 1012 1013

  /// The alignment of the origin, relative to the size of the box.
  ///
  /// This is equivalent to setting an origin based on the size of the box.
1014 1015 1016 1017 1018 1019 1020 1021 1022
  /// If it is specified at the same time as the [origin], both are applied.
  ///
  /// An [AlignmentDirectional.start] value is the same as an [Alignment]
  /// whose [Alignment.x] value is `-1.0` if [textDirection] is
  /// [TextDirection.ltr], and `1.0` if [textDirection] is [TextDirection.rtl].
  /// Similarly [AlignmentDirectional.end] is the same as an [Alignment]
  /// whose [Alignment.x] value is `1.0` if [textDirection] is
  /// [TextDirection.ltr], and `-1.0` if [textDirection] is [TextDirection.rtl].
  final AlignmentGeometry alignment;
1023

1024
  /// Whether to apply the transformation when performing hit tests.
1025 1026
  final bool transformHitTests;

1027
  @override
1028 1029 1030 1031 1032
  RenderTransform createRenderObject(BuildContext context) {
    return new RenderTransform(
      transform: transform,
      origin: origin,
      alignment: alignment,
1033
      textDirection: Directionality.of(context),
1034 1035 1036
      transformHitTests: transformHitTests
    );
  }
1037

1038
  @override
1039
  void updateRenderObject(BuildContext context, RenderTransform renderObject) {
1040 1041 1042 1043
    renderObject
      ..transform = transform
      ..origin = origin
      ..alignment = alignment
1044
      ..textDirection = Directionality.of(context)
1045
      ..transformHitTests = transformHitTests;
1046 1047 1048
  }
}

1049
/// A widget that can be targeted by a [CompositedTransformFollower].
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
///
/// When this widget is composited during the compositing phase (which comes
/// after the paint phase, as described in [WidgetsBinding.drawFrame]), it
/// updates the [link] object so that any [CompositedTransformFollower] widgets
/// that are subsequently composited in the same frame and were given the same
/// [LayerLink] can position themselves at the same screen location.
///
/// A single [CompositedTransformTarget] can be followed by multiple
/// [CompositedTransformFollower] widgets.
///
/// The [CompositedTransformTarget] must come earlier in the paint order than
/// any linked [CompositedTransformFollower]s.
///
/// See also:
///
///  * [CompositedTransformFollower], the widget that can target this one.
///  * [LeaderLayer], the layer that implements this widget's logic.
class CompositedTransformTarget extends SingleChildRenderObjectWidget {
  /// Creates a composited transform target widget.
  ///
  /// The [link] property must not be null, and must not be currently being used
  /// by any other [CompositedTransformTarget] object that is in the tree.
  const CompositedTransformTarget({
    Key key,
    @required this.link,
    Widget child,
  }) : assert(link != null),
       super(key: key, child: child);

  /// The link object that connects this [CompositedTransformTarget] with one or
  /// more [CompositedTransformFollower]s.
  ///
  /// This property must not be null. The object must not be associated with
  /// another [CompositedTransformTarget] that is also being painted.
  final LayerLink link;

  @override
  RenderLeaderLayer createRenderObject(BuildContext context) {
    return new RenderLeaderLayer(
      link: link,
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderLeaderLayer renderObject) {
    renderObject
      ..link = link;
  }
}

/// A widget that follows a [CompositedTransformTarget].
///
/// When this widget is composited during the compositing phase (which comes
/// after the paint phase, as described in [WidgetsBinding.drawFrame]), it
/// applies a transformation that causes it to provide its child with a
/// coordinate space that matches that of the linked [CompositedTransformTarget]
/// widget, offset by [offset].
///
/// The [LayerLink] object used as the [link] must be the same object as that
/// provided to the matching [CompositedTransformTarget].
///
/// The [CompositedTransformTarget] must come earlier in the paint order than
/// this [CompositedTransformFollower].
///
/// Hit testing on descendants of this widget will only work if the target
/// position is within the box that this widget's parent considers to be
/// hitable. If the parent covers the screen, this is trivially achievable, so
/// this widget is usually used as the root of an [OverlayEntry] in an app-wide
/// [Overlay] (e.g. as created by the [MaterialApp] widget's [Navigator]).
///
/// See also:
///
///  * [CompositedTransformTarget], the widget that this widget can target.
///  * [FollowerLayer], the layer that implements this widget's logic.
///  * [Transform], which applies an arbitrary transform to a child.
class CompositedTransformFollower extends SingleChildRenderObjectWidget {
  /// Creates a composited transform target widget.
  ///
  /// The [link] property must not be null. If it was also provided to a
  /// [CompositedTransformTarget], that widget must come earlier in the paint
  /// order.
  ///
  /// The [showWhenUnlinked] and [offset] properties must also not be null.
  const CompositedTransformFollower({
    Key key,
    @required this.link,
1136 1137
    this.showWhenUnlinked = true,
    this.offset = Offset.zero,
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    Widget child,
  }) : assert(link != null),
       assert(showWhenUnlinked != null),
       assert(offset != null),
       super(key: key, child: child);

  /// The link object that connects this [CompositedTransformFollower] with a
  /// [CompositedTransformTarget].
  ///
  /// This property must not be null.
  final LayerLink link;

  /// Whether to show the widget's contents when there is no corresponding
  /// [CompositedTransformTarget] with the same [link].
  ///
  /// When the widget is linked, the child is positioned such that it has the
  /// same global position as the linked [CompositedTransformTarget].
  ///
  /// When the widget is not linked, then: if [showWhenUnlinked] is true, the
  /// child is visible and not repositioned; if it is false, then child is
  /// hidden.
  final bool showWhenUnlinked;

  /// The offset to apply to the origin of the linked
  /// [CompositedTransformTarget] to obtain this widget's origin.
  final Offset offset;

  @override
  RenderFollowerLayer createRenderObject(BuildContext context) {
    return new RenderFollowerLayer(
      link: link,
      showWhenUnlinked: showWhenUnlinked,
      offset: offset,
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderFollowerLayer renderObject) {
    renderObject
      ..link = link
      ..showWhenUnlinked = showWhenUnlinked
      ..offset = offset;
  }
}

Adam Barth's avatar
Adam Barth committed
1183
/// Scales and positions its child within itself according to [fit].
1184 1185 1186 1187 1188
///
/// See also:
///
///  * [Transform], which applies an arbitrary transform to its child widget at
///    paint time.
1189
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
Adam Barth's avatar
Adam Barth committed
1190 1191 1192 1193
class FittedBox extends SingleChildRenderObjectWidget {
  /// Creates a widget that scales and positions its child within itself according to [fit].
  ///
  /// The [fit] and [alignment] arguments must not be null.
1194
  const FittedBox({
Adam Barth's avatar
Adam Barth committed
1195
    Key key,
1196 1197
    this.fit = BoxFit.contain,
    this.alignment = Alignment.center,
Ian Hickson's avatar
Ian Hickson committed
1198
    Widget child,
1199 1200 1201
  }) : assert(fit != null),
       assert(alignment != null),
       super(key: key, child: child);
Adam Barth's avatar
Adam Barth committed
1202 1203

  /// How to inscribe the child into the space allocated during layout.
1204
  final BoxFit fit;
Adam Barth's avatar
Adam Barth committed
1205 1206 1207

  /// How to align the child within its parent's bounds.
  ///
1208
  /// An alignment of (-1.0, -1.0) aligns the child to the top-left corner of its
1209
  /// parent's bounds. An alignment of (1.0, 0.0) aligns the child to the middle
Adam Barth's avatar
Adam Barth committed
1210
  /// of the right edge of its parent's bounds.
1211 1212 1213 1214 1215 1216 1217 1218 1219
  ///
  /// Defaults to [Alignment.center].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
Ian Hickson's avatar
Ian Hickson committed
1220
  final AlignmentGeometry alignment;
Adam Barth's avatar
Adam Barth committed
1221 1222

  @override
Ian Hickson's avatar
Ian Hickson committed
1223 1224 1225 1226 1227 1228 1229
  RenderFittedBox createRenderObject(BuildContext context) {
    return new RenderFittedBox(
      fit: fit,
      alignment: alignment,
      textDirection: Directionality.of(context),
    );
  }
Adam Barth's avatar
Adam Barth committed
1230 1231 1232 1233 1234

  @override
  void updateRenderObject(BuildContext context, RenderFittedBox renderObject) {
    renderObject
      ..fit = fit
Ian Hickson's avatar
Ian Hickson committed
1235 1236 1237 1238 1239
      ..alignment = alignment
      ..textDirection = Directionality.of(context);
  }

  @override
1240 1241 1242 1243
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<BoxFit>('fit', fit));
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
Adam Barth's avatar
Adam Barth committed
1244 1245 1246
  }
}

1247 1248 1249 1250 1251 1252 1253 1254 1255
/// Applies a translation transformation before painting its child.
///
/// The translation is expressed as a [Offset] scaled to the child's size. For
/// example, an [Offset] with a `dx` of 0.25 will result in a horizontal
/// translation of one quarter the width of the child.
///
/// Hit tests will only be detected inside the bounds of the
/// [FractionalTranslation], even if the contents are offset such that
/// they overflow.
1256 1257 1258
///
/// See also:
///
1259 1260 1261 1262
///  * [Transform], which applies an arbitrary transform to its child widget at
///    paint time.
///  * [new Transform.translate], which applies an absolute offset translation
///    transformation instead of an offset scaled to the child.
1263
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1264
class FractionalTranslation extends SingleChildRenderObjectWidget {
1265 1266 1267
  /// Creates a widget that translates its child's painting.
  ///
  /// The [translation] argument must not be null.
1268
  const FractionalTranslation({
1269
    Key key,
1270
    @required this.translation,
1271
    this.transformHitTests = true,
1272
    Widget child,
1273 1274
  }) : assert(translation != null),
       super(key: key, child: child);
1275

1276 1277 1278 1279 1280
  /// The translation to apply to the child, scaled to the child's size.
  ///
  /// For example, an [Offset] with a `dx` of 0.25 will result in a horizontal
  /// translation of one quarter the width of the child.
  final Offset translation;
1281 1282 1283 1284

  /// Whether to apply the translation when performing hit tests.
  final bool transformHitTests;

1285
  @override
1286 1287 1288 1289 1290 1291
  RenderFractionalTranslation createRenderObject(BuildContext context) {
    return new RenderFractionalTranslation(
      translation: translation,
      transformHitTests: transformHitTests,
    );
  }
1292

1293
  @override
1294
  void updateRenderObject(BuildContext context, RenderFractionalTranslation renderObject) {
1295 1296 1297
    renderObject
      ..translation = translation
      ..transformHitTests = transformHitTests;
1298 1299 1300
  }
}

1301
/// A widget that rotates its child by a integral number of quarter turns.
1302 1303 1304 1305
///
/// Unlike [Transform], which applies a transform just prior to painting,
/// this object applies its rotation prior to layout, which means the entire
/// rotated box consumes only as much space as required by the rotated child.
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
///
/// ## Sample code
///
/// This snippet rotates the child (some [Text]) so that it renders from bottom
/// to top, like an axis label on a graph:
///
/// ```dart
/// new RotatedBox(
///   quarterTurns: 3,
///   child: const Text('Hello World!'),
/// )
/// ```
///
/// See also:
///
///  * [Transform], which is a paint effect that allows you to apply an
///    arbitrary transform to a child.
1323
///  * [new Transform.rotate], which applies a rotation paint effect.
1324
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1325
class RotatedBox extends SingleChildRenderObjectWidget {
1326 1327 1328
  /// A widget that rotates its child.
  ///
  /// The [quarterTurns] argument must not be null.
1329
  const RotatedBox({
1330 1331
    Key key,
    @required this.quarterTurns,
1332
    Widget child,
1333 1334
  }) : assert(quarterTurns != null),
       super(key: key, child: child);
1335 1336 1337 1338

  /// The number of clockwise quarter turns the child should be rotated.
  final int quarterTurns;

1339
  @override
1340 1341
  RenderRotatedBox createRenderObject(BuildContext context) => new RenderRotatedBox(quarterTurns: quarterTurns);

1342
  @override
1343 1344 1345 1346 1347
  void updateRenderObject(BuildContext context, RenderRotatedBox renderObject) {
    renderObject.quarterTurns = quarterTurns;
  }
}

1348
/// A widget that insets its child by the given padding.
1349 1350 1351 1352 1353
///
/// When passing layout constraints to its child, padding shrinks the
/// constraints by the given padding, causing the child to layout at a smaller
/// size. Padding then sizes itself to its child's size, inflated by the
/// padding, effectively creating empty space around the child.
1354
///
1355 1356
/// ## Sample code
///
1357 1358
/// This snippet indents the child (a [Card] with some [Text]) by eight pixels
/// in each direction:
1359 1360 1361 1362 1363 1364 1365 1366
///
/// ```dart
/// new Padding(
///   padding: new EdgeInsets.all(8.0),
///   child: const Card(child: const Text('Hello World!')),
/// )
/// ```
///
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
/// ## Design discussion
///
/// ### Why use a [Padding] widget rather than a [Container] with a [Container.padding] property?
///
/// There isn't really any difference between the two. If you supply a
/// [Container.padding] argument, [Container] simply builds a [Padding] widget
/// for you.
///
/// [Container] doesn't implement its properties directly. Instead, [Container]
/// combines a number of simpler widgets together into a convenient package. For
/// example, the [Container.padding] property causes the container to build a
/// [Padding] widget and the [Container.decoration] property causes the
/// container to build a [DecoratedBox] widget. If you find [Container]
/// convenient, feel free to use it. If not, feel free to build these simpler
/// widgets in whatever combination meets your needs.
///
/// In fact, the majority of widgets in Flutter are simply combinations of other
/// simpler widgets. Composition, rather than inheritance, is the primary
1385
/// mechanism for building up widgets.
1386 1387 1388 1389
///
/// See also:
///
///  * [EdgeInsets], the class that is used to describe the padding dimensions.
1390
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1391
class Padding extends SingleChildRenderObjectWidget {
1392 1393 1394
  /// Creates a widget that insets its child.
  ///
  /// The [padding] argument must not be null.
1395
  const Padding({
1396 1397
    Key key,
    @required this.padding,
1398
    Widget child,
1399 1400
  }) : assert(padding != null),
       super(key: key, child: child);
1401

1402
  /// The amount of space by which to inset the child.
1403
  final EdgeInsetsGeometry padding;
1404

1405
  @override
1406 1407 1408 1409 1410 1411
  RenderPadding createRenderObject(BuildContext context) {
    return new RenderPadding(
      padding: padding,
      textDirection: Directionality.of(context),
    );
  }
1412

1413
  @override
1414
  void updateRenderObject(BuildContext context, RenderPadding renderObject) {
1415 1416 1417
    renderObject
      ..padding = padding
      ..textDirection = Directionality.of(context);
1418
  }
1419 1420

  @override
1421 1422 1423
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
1424
  }
1425 1426
}

1427 1428
/// A widget that aligns its child within itself and optionally sizes itself
/// based on the child's size.
1429 1430 1431
///
/// For example, to align a box at the bottom right, you would pass this box a
/// tight constraint that is bigger than the child's natural size,
1432
/// with an alignment of [Alignment.bottomRight].
Adam Barth's avatar
Adam Barth committed
1433
///
1434 1435 1436 1437 1438
/// This widget will be as big as possible if its dimensions are constrained and
/// [widthFactor] and [heightFactor] are null. If a dimension is unconstrained
/// and the corresponding size factor is null then the widget will match its
/// child's size in that dimension. If a size factor is non-null then the
/// corresponding dimension of this widget will be the product of the child's
Hans Muller's avatar
Hans Muller committed
1439 1440
/// dimension and the size factor. For example if widthFactor is 2.0 then
/// the width of this widget will always be twice its child's width.
Adam Barth's avatar
Adam Barth committed
1441 1442 1443
///
/// See also:
///
1444 1445
///  * [CustomSingleChildLayout], which uses a delegate to control the layout of
///    a single child.
1446
///  * [Center], which is the same as [Align] but with the [alignment] always
1447
///    set to [Alignment.center].
1448 1449 1450
///  * [FractionallySizedBox], which sizes its child based on a fraction of its
///    own size and positions the child according to an [Alignment] value.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1451
class Align extends SingleChildRenderObjectWidget {
Adam Barth's avatar
Adam Barth committed
1452 1453
  /// Creates an alignment widget.
  ///
1454
  /// The alignment defaults to [Alignment.center].
1455
  const Align({
1456
    Key key,
1457
    this.alignment = Alignment.center,
1458 1459
    this.widthFactor,
    this.heightFactor,
1460
    Widget child
1461 1462 1463 1464
  }) : assert(alignment != null),
       assert(widthFactor == null || widthFactor >= 0.0),
       assert(heightFactor == null || heightFactor >= 0.0),
       super(key: key, child: child);
1465

1466 1467
  /// How to align the child.
  ///
Ian Hickson's avatar
Ian Hickson committed
1468
  /// The x and y values of the [Alignment] control the horizontal and vertical
1469
  /// alignment, respectively. An x value of -1.0 means that the left edge of
1470 1471 1472
  /// the child is aligned with the left edge of the parent whereas an x value
  /// of 1.0 means that the right edge of the child is aligned with the right
  /// edge of the parent. Other values interpolate (and extrapolate) linearly.
1473
  /// For example, a value of 0.0 means that the center of the child is aligned
1474
  /// with the center of the parent.
Ian Hickson's avatar
Ian Hickson committed
1475 1476 1477 1478 1479 1480 1481
  ///
  /// See also:
  ///
  ///  * [Alignment], which has more details and some convenience constants for
  ///    common positions.
  ///  * [AlignmentDirectional], which has a horizontal coordinate orientation
  ///    that depends on the [TextDirection].
1482
  final AlignmentGeometry alignment;
1483

1484
  /// If non-null, sets its width to the child's width multiplied by this factor.
1485 1486
  ///
  /// Can be both greater and less than 1.0 but must be positive.
1487
  final double widthFactor;
1488

1489
  /// If non-null, sets its height to the child's height multiplied by this factor.
1490 1491
  ///
  /// Can be both greater and less than 1.0 but must be positive.
1492
  final double heightFactor;
1493

1494
  @override
1495 1496 1497 1498 1499 1500 1501 1502
  RenderPositionedBox createRenderObject(BuildContext context) {
    return new RenderPositionedBox(
      alignment: alignment,
      widthFactor: widthFactor,
      heightFactor: heightFactor,
      textDirection: Directionality.of(context),
    );
  }
1503

1504
  @override
1505
  void updateRenderObject(BuildContext context, RenderPositionedBox renderObject) {
1506 1507 1508
    renderObject
      ..alignment = alignment
      ..widthFactor = widthFactor
1509 1510
      ..heightFactor = heightFactor
      ..textDirection = Directionality.of(context);
1511
  }
1512 1513

  @override
1514 1515 1516 1517 1518
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(new DoubleProperty('widthFactor', widthFactor, defaultValue: null));
    properties.add(new DoubleProperty('heightFactor', heightFactor, defaultValue: null));
1519
  }
1520 1521
}

1522
/// A widget that centers its child within itself.
Adam Barth's avatar
Adam Barth committed
1523
///
1524 1525 1526 1527 1528 1529 1530 1531
/// This widget will be as big as possible if its dimensions are constrained and
/// [widthFactor] and [heightFactor] are null. If a dimension is unconstrained
/// and the corresponding size factor is null then the widget will match its
/// child's size in that dimension. If a size factor is non-null then the
/// corresponding dimension of this widget will be the product of the child's
/// dimension and the size factor. For example if widthFactor is 2.0 then
/// the width of this widget will always be twice its child's width.
///
Adam Barth's avatar
Adam Barth committed
1532 1533
/// See also:
///
1534 1535
///  * [Align], which lets you arbitrarily position a child within itself,
///    rather than just centering it.
1536 1537 1538 1539 1540
///  * [Row], a widget that displays its children in a horizontal array.
///  * [Column], a widget that displays its children in a vertical array.
///  * [Container], a convenience widget that combines common painting,
///    positioning, and sizing widgets.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1541
class Center extends Align {
1542
  /// Creates a widget that centers its child.
1543
  const Center({ Key key, double widthFactor, double heightFactor, Widget child })
1544
    : super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
1545 1546
}

1547
/// A widget that defers the layout of its single child to a delegate.
1548 1549 1550 1551 1552
///
/// The delegate can determine the layout constraints for the child and can
/// decide where to position the child. The delegate can also determine the size
/// of the parent, but the size of the parent cannot depend on the size of the
/// child.
Adam Barth's avatar
Adam Barth committed
1553 1554 1555
///
/// See also:
///
1556 1557
///  * [SingleChildLayoutDelegate], which controls the layout of the child.
///  * [Align], which sizes itself based on its child's size and positions
1558
///    the child according to an [Alignment] value.
1559
///  * [FractionallySizedBox], which sizes its child based on a fraction of its own
1560
///    size and positions the child according to an [Alignment] value.
1561 1562
///  * [CustomMultiChildLayout], which uses a delegate to position multiple
///    children.
1563
class CustomSingleChildLayout extends SingleChildRenderObjectWidget {
Adam Barth's avatar
Adam Barth committed
1564 1565
  /// Creates a custom single child layout.
  ///
1566
  /// The [delegate] argument must not be null.
1567
  const CustomSingleChildLayout({
Adam Barth's avatar
Adam Barth committed
1568
    Key key,
1569
    @required this.delegate,
Adam Barth's avatar
Adam Barth committed
1570
    Widget child
1571 1572
  }) : assert(delegate != null),
       super(key: key, child: child);
Adam Barth's avatar
Adam Barth committed
1573

Adam Barth's avatar
Adam Barth committed
1574
  /// The delegate that controls the layout of the child.
1575
  final SingleChildLayoutDelegate delegate;
Adam Barth's avatar
Adam Barth committed
1576

1577
  @override
1578 1579 1580
  RenderCustomSingleChildLayoutBox createRenderObject(BuildContext context) {
    return new RenderCustomSingleChildLayoutBox(delegate: delegate);
  }
Adam Barth's avatar
Adam Barth committed
1581

1582
  @override
1583
  void updateRenderObject(BuildContext context, RenderCustomSingleChildLayoutBox renderObject) {
1584 1585 1586 1587
    renderObject.delegate = delegate;
  }
}

1588
/// Metadata for identifying children in a [CustomMultiChildLayout].
1589
///
1590 1591 1592
/// The [MultiChildLayoutDelegate.hasChild],
/// [MultiChildLayoutDelegate.layoutChild], and
/// [MultiChildLayoutDelegate.positionChild] methods use these identifiers.
1593
class LayoutId extends ParentDataWidget<CustomMultiChildLayout> {
Adam Barth's avatar
Adam Barth committed
1594 1595 1596
  /// Marks a child with a layout identifier.
  ///
  /// Both the child and the id arguments must not be null.
1597 1598
  LayoutId({
    Key key,
1599
    @required this.id,
1600
    @required Widget child
1601 1602 1603
  }) : assert(child != null),
       assert(id != null),
       super(key: key ?? new ValueKey<Object>(id), child: child);
1604

1605
  /// An object representing the identity of this child.
1606 1607 1608
  ///
  /// The [id] needs to be unique among the children that the
  /// [CustomMultiChildLayout] manages.
1609 1610
  final Object id;

1611
  @override
1612 1613 1614 1615 1616
  void applyParentData(RenderObject renderObject) {
    assert(renderObject.parentData is MultiChildLayoutParentData);
    final MultiChildLayoutParentData parentData = renderObject.parentData;
    if (parentData.id != id) {
      parentData.id = id;
1617
      final AbstractNode targetParent = renderObject.parent;
1618 1619 1620 1621 1622
      if (targetParent is RenderObject)
        targetParent.markNeedsLayout();
    }
  }

1623
  @override
1624 1625 1626
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<Object>('id', id));
1627 1628 1629
  }
}

1630
/// A widget that uses a delegate to size and position multiple children.
1631 1632 1633 1634 1635
///
/// The delegate can determine the layout constraints for each child and can
/// decide where to position each child. The delegate can also determine the
/// size of the parent, but the size of the parent cannot depend on the sizes of
/// the children.
Adam Barth's avatar
Adam Barth committed
1636
///
1637 1638 1639 1640 1641 1642 1643 1644 1645
/// [CustomMultiChildLayout] is appropriate when there are complex relationships
/// between the size and positioning of a multiple widgets. To control the
/// layout of a single child, [CustomSingleChildLayout] is more appropriate. For
/// simple cases, such as aligning a widget to one or another edge, the [Stack]
/// widget is more appropriate.
///
/// Each child must be wrapped in a [LayoutId] widget to identify the widget for
/// the delegate.
///
Adam Barth's avatar
Adam Barth committed
1646 1647
/// See also:
///
1648 1649 1650 1651 1652 1653 1654
/// * [MultiChildLayoutDelegate], for details about how to control the layout of
///   the children.
/// * [CustomSingleChildLayout], which uses a delegate to control the layout of
///   a single child.
/// * [Stack], which arranges children relative to the edges of the container.
/// * [Flow], which provides paint-time control of its children using transform
///   matrices.
1655
class CustomMultiChildLayout extends MultiChildRenderObjectWidget {
Adam Barth's avatar
Adam Barth committed
1656 1657
  /// Creates a custom multi-child layout.
  ///
1658
  /// The [delegate] argument must not be null.
1659
  CustomMultiChildLayout({
1660
    Key key,
1661
    @required this.delegate,
1662
    List<Widget> children = const <Widget>[],
1663 1664
  }) : assert(delegate != null),
       super(key: key, children: children);
1665

1666
  /// The delegate that controls the layout of the children.
1667 1668
  final MultiChildLayoutDelegate delegate;

1669
  @override
1670
  RenderCustomMultiChildLayoutBox createRenderObject(BuildContext context) {
1671 1672 1673
    return new RenderCustomMultiChildLayoutBox(delegate: delegate);
  }

1674
  @override
1675
  void updateRenderObject(BuildContext context, RenderCustomMultiChildLayoutBox renderObject) {
Adam Barth's avatar
Adam Barth committed
1676 1677 1678 1679
    renderObject.delegate = delegate;
  }
}

1680 1681
/// A box with a specified size.
///
Adam Barth's avatar
Adam Barth committed
1682 1683 1684 1685 1686 1687 1688
/// If given a child, this widget forces its child to have a specific width
/// and/or height (assuming values are permitted by this widget's parent). If
/// either the width or height is null, this widget will size itself to match
/// the child's size in that dimension.
///
/// If not given a child, this widget will size itself to the given width and
/// height, treating nulls as zero.
Ian Hickson's avatar
Ian Hickson committed
1689 1690 1691
///
/// The [new SizedBox.expand] constructor can be used to make a [SizedBox] that
/// sizes itself to fit the parent. It is equivalent to setting [width] and
1692
/// [height] to [double.infinity].
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
///
/// ## Sample code
///
/// This snippet makes the child widget (a [Card] with some [Text]) have the
/// exact size 200x300, parental constraints permitting:
///
/// ```dart
/// new SizedBox(
///   width: 200.0,
///   height: 300.0,
///   child: const Card(child: const Text('Hello World!')),
/// )
/// ```
///
/// See also:
///
///  * [ConstrainedBox], a more generic version of this class that takes
///    arbitrary [BoxConstraints] instead of an explicit width and height.
1711 1712
///  * [UnconstrainedBox], a container that tries to let its child draw without
///    constraints.
1713 1714 1715
///  * [FractionallySizedBox], a widget that sizes its child to a fraction of
///    the total available space.
///  * [AspectRatio], a widget that attempts to fit within the parent's
1716
///    constraints while also sizing its child to match a given aspect ratio.
1717 1718
///  * [FittedBox], which sizes and positions its child widget to fit the parent
///    according to a given [BoxFit] discipline.
1719
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1720
class SizedBox extends SingleChildRenderObjectWidget {
1721 1722 1723
  /// Creates a fixed size box. The [width] and [height] parameters can be null
  /// to indicate that the size of the box should not be constrained in
  /// the corresponding dimension.
1724
  const SizedBox({ Key key, this.width, this.height, Widget child })
1725 1726
    : super(key: key, child: child);

1727
  /// Creates a box that will become as large as its parent allows.
Ian Hickson's avatar
Ian Hickson committed
1728
  const SizedBox.expand({ Key key, Widget child })
1729 1730
    : width = double.infinity,
      height = double.infinity,
Ian Hickson's avatar
Ian Hickson committed
1731 1732
      super(key: key, child: child);

1733 1734 1735 1736 1737 1738
  /// Creates a box that will become as small as its parent allows.
  const SizedBox.shrink({ Key key, Widget child })
    : width = 0.0,
      height = 0.0,
      super(key: key, child: child);

1739 1740 1741 1742 1743 1744
  /// Creates a box with the specified size.
  SizedBox.fromSize({ Key key, Widget child, Size size })
    : width = size?.width,
      height = size?.height,
      super(key: key, child: child);

1745
  /// If non-null, requires the child to have exactly this width.
1746
  final double width;
1747 1748

  /// If non-null, requires the child to have exactly this height.
1749 1750
  final double height;

1751
  @override
1752 1753 1754 1755 1756
  RenderConstrainedBox createRenderObject(BuildContext context) {
    return new RenderConstrainedBox(
      additionalConstraints: _additionalConstraints,
    );
  }
1757

1758
  BoxConstraints get _additionalConstraints {
1759
    return new BoxConstraints.tightFor(width: width, height: height);
1760 1761
  }

1762
  @override
1763
  void updateRenderObject(BuildContext context, RenderConstrainedBox renderObject) {
1764
    renderObject.additionalConstraints = _additionalConstraints;
1765
  }
1766

Ian Hickson's avatar
Ian Hickson committed
1767 1768
  @override
  String toStringShort() {
1769 1770 1771 1772 1773 1774 1775 1776
    String type;
    if (width == double.infinity && height == double.infinity) {
      type = '$runtimeType.expand';
    } else if (width == 0.0 && height == 0.0) {
      type = '$runtimeType.shrink';
    } else {
      type = '$runtimeType';
    }
Ian Hickson's avatar
Ian Hickson committed
1777 1778 1779
    return key == null ? '$type' : '$type-$key';
  }

1780
  @override
1781 1782
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1783 1784 1785 1786 1787 1788 1789
    DiagnosticLevel level;
    if ((width == double.infinity && height == double.infinity) ||
        (width == 0.0 && height == 0.0)) {
      level = DiagnosticLevel.hidden;
    } else {
      level = DiagnosticLevel.info;
    }
1790 1791
    properties.add(new DoubleProperty('width', width, defaultValue: null, level: level));
    properties.add(new DoubleProperty('height', height, defaultValue: null, level: level));
1792
  }
1793 1794
}

1795
/// A widget that imposes additional constraints on its child.
1796 1797
///
/// For example, if you wanted [child] to have a minimum height of 50.0 logical
1798
/// pixels, you could use `const BoxConstraints(minHeight: 50.0)` as the
1799
/// [constraints].
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
///
/// ## Sample code
///
/// This snippet makes the child widget (a [Card] with some [Text]) fill the
/// parent, by applying [BoxConstraints.expand] constraints:
///
/// ```dart
/// new ConstrainedBox(
///   constraints: const BoxConstraints.expand(),
///   child: const Card(child: const Text('Hello World!')),
/// )
/// ```
///
Ian Hickson's avatar
Ian Hickson committed
1813
/// The same behavior can be obtained using the [new SizedBox.expand] widget.
1814 1815 1816 1817
///
/// See also:
///
///  * [BoxConstraints], the class that describes constraints.
1818 1819
///  * [UnconstrainedBox], a container that tries to let its child draw without
///    constraints.
1820 1821
///  * [SizedBox], which lets you specify tight constraints by explicitly
///    specifying the height or width.
1822 1823
///  * [FractionallySizedBox], which sizes its child based on a fraction of its
///    own size and positions the child according to an [Alignment] value.
1824
///  * [AspectRatio], a widget that attempts to fit within the parent's
1825 1826
///    constraints while also sizing its child to match a given aspect ratio.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1827
class ConstrainedBox extends SingleChildRenderObjectWidget {
1828 1829 1830 1831 1832 1833 1834
  /// Creates a widget that imposes additional constraints on its child.
  ///
  /// The [constraints] argument must not be null.
  ConstrainedBox({
    Key key,
    @required this.constraints,
    Widget child
1835
  }) : assert(constraints != null),
1836 1837
       assert(constraints.debugAssertIsValid()),
       super(key: key, child: child);
1838

1839
  /// The additional constraints to impose on the child.
1840 1841
  final BoxConstraints constraints;

1842
  @override
1843 1844 1845
  RenderConstrainedBox createRenderObject(BuildContext context) {
    return new RenderConstrainedBox(additionalConstraints: constraints);
  }
1846

1847
  @override
1848
  void updateRenderObject(BuildContext context, RenderConstrainedBox renderObject) {
1849
    renderObject.additionalConstraints = constraints;
1850
  }
1851

1852
  @override
1853 1854 1855
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<BoxConstraints>('constraints', constraints, showName: false));
1856
  }
1857 1858
}

1859 1860 1861 1862
/// A widget that imposes no constraints on its child, allowing it to render
/// at its "natural" size.
///
/// This allows a child to render at the size it would render if it were alone
1863 1864 1865 1866 1867
/// on an infinite canvas with no constraints. This container will then attempt
/// to adopt the same size, within the limits of its own constraints. If it ends
/// up with a different size, it will align the child based on [alignment].
/// If the box cannot expand enough to accommodate the entire child, the
/// child will be clipped.
1868 1869 1870 1871 1872 1873 1874
///
/// In debug mode, if the child overflows the container, a warning will be
/// printed on the console, and black and yellow striped areas will appear where
/// the overflow occurs.
///
/// See also:
///
1875 1876 1877
///  * [ConstrainedBox], for a box which imposes constraints on its child.
///  * [Align], which loosens the constraints given to the child rather than
///    removing them entirely.
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
///  * [Container], a convenience widget that combines common painting,
///    positioning, and sizing widgets.
///  * [OverflowBox], a widget that imposes different constraints on its child
///    than it gets from its parent, possibly allowing the child to overflow
///    the parent.
class UnconstrainedBox extends SingleChildRenderObjectWidget {
  /// Creates a widget that imposes no constraints on its child, allowing it to
  /// render at its "natural" size. If the child overflows the parents
  /// constraints, a warning will be given in debug mode.
  const UnconstrainedBox({
    Key key,
    Widget child,
    this.textDirection,
1891
    this.alignment = Alignment.center,
1892
    this.constrainedAxis,
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
  }) : assert(alignment != null),
       super(key: key, child: child);

  /// The text direction to use when interpreting the [alignment] if it is an
  /// [AlignmentDirectional].
  final TextDirection textDirection;

  /// The alignment to use when laying out the child.
  ///
  /// If this is an [AlignmentDirectional], then [textDirection] must not be
  /// null.
  ///
  /// See also:
  ///
  ///  * [Alignment] for non-[Directionality]-aware alignments.
  ///  * [AlignmentDirectional] for [Directionality]-aware alignments.
  final AlignmentGeometry alignment;

1911 1912 1913
  /// The axis to retain constraints on, if any.
  ///
  /// If not set, or set to null (the default), neither axis will retain its
1914
  /// constraints. If set to [Axis.vertical], then vertical constraints will
1915 1916 1917
  /// be retained, and if set to [Axis.horizontal], then horizontal constraints
  /// will be retained.
  final Axis constrainedAxis;
1918

1919 1920 1921 1922
  @override
  void updateRenderObject(BuildContext context, covariant RenderUnconstrainedBox renderObject) {
    renderObject
      ..textDirection = textDirection ?? Directionality.of(context)
1923 1924
      ..alignment = alignment
      ..constrainedAxis = constrainedAxis;
1925 1926 1927 1928 1929 1930
  }

  @override
  RenderUnconstrainedBox createRenderObject(BuildContext context) => new RenderUnconstrainedBox(
    textDirection: textDirection ?? Directionality.of(context),
    alignment: alignment,
1931
    constrainedAxis: constrainedAxis,
1932 1933 1934
  );

  @override
1935 1936 1937 1938 1939
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(new DiagnosticsProperty<Axis>('constrainedAxis', null));
    properties.add(new DiagnosticsProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
1940 1941 1942
  }
}

1943
/// A widget that sizes its child to a fraction of the total available space.
1944 1945
/// For more details about the layout algorithm, see
/// [RenderFractionallySizedOverflowBox].
1946
///
1947
/// See also:
1948
///
1949 1950 1951 1952 1953 1954
///  * [Align], which sizes itself based on its child's size and positions
///    the child according to an [Alignment] value.
///  * [OverflowBox], a widget that imposes different constraints on its child
///    than it gets from its parent, possibly allowing the child to overflow the
///    parent.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
1955
class FractionallySizedBox extends SingleChildRenderObjectWidget {
1956 1957 1958 1959
  /// Creates a widget that sizes its child to a fraction of the total available space.
  ///
  /// If non-null, the [widthFactor] and [heightFactor] arguments must be
  /// non-negative.
1960
  const FractionallySizedBox({
1961
    Key key,
1962
    this.alignment = Alignment.center,
1963 1964
    this.widthFactor,
    this.heightFactor,
1965
    Widget child,
1966 1967 1968 1969
  }) : assert(alignment != null),
       assert(widthFactor == null || widthFactor >= 0.0),
       assert(heightFactor == null || heightFactor >= 0.0),
       super(key: key, child: child);
Hixie's avatar
Hixie committed
1970

1971
  /// If non-null, the fraction of the incoming width given to the child.
1972 1973
  ///
  /// If non-null, the child is given a tight width constraint that is the max
1974
  /// incoming width constraint multiplied by this factor.
1975 1976 1977
  ///
  /// If null, the incoming width constraints are passed to the child
  /// unmodified.
1978
  final double widthFactor;
1979

Hans Muller's avatar
Hans Muller committed
1980
  /// If non-null, the fraction of the incoming height given to the child.
1981 1982
  ///
  /// If non-null, the child is given a tight height constraint that is the max
1983
  /// incoming height constraint multiplied by this factor.
1984 1985 1986
  ///
  /// If null, the incoming height constraints are passed to the child
  /// unmodified.
1987
  final double heightFactor;
Hixie's avatar
Hixie committed
1988

1989 1990 1991
  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
1992
  /// alignment, respectively. An x value of -1.0 means that the left edge of
1993 1994 1995
  /// the child is aligned with the left edge of the parent whereas an x value
  /// of 1.0 means that the right edge of the child is aligned with the right
  /// edge of the parent. Other values interpolate (and extrapolate) linearly.
1996
  /// For example, a value of 0.0 means that the center of the child is aligned
1997
  /// with the center of the parent.
1998 1999 2000 2001 2002 2003 2004 2005 2006
  ///
  /// Defaults to [Alignment.center].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
2007
  final AlignmentGeometry alignment;
2008

2009
  @override
2010 2011 2012 2013
  RenderFractionallySizedOverflowBox createRenderObject(BuildContext context) {
    return new RenderFractionallySizedOverflowBox(
      alignment: alignment,
      widthFactor: widthFactor,
2014 2015
      heightFactor: heightFactor,
      textDirection: Directionality.of(context),
2016 2017
    );
  }
Hixie's avatar
Hixie committed
2018

2019
  @override
2020
  void updateRenderObject(BuildContext context, RenderFractionallySizedOverflowBox renderObject) {
2021
    renderObject
2022
      ..alignment = alignment
2023
      ..widthFactor = widthFactor
2024 2025
      ..heightFactor = heightFactor
      ..textDirection = Directionality.of(context);
Hixie's avatar
Hixie committed
2026
  }
2027

2028
  @override
2029 2030 2031 2032 2033
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(new DoubleProperty('widthFactor', widthFactor, defaultValue: null));
    properties.add(new DoubleProperty('heightFactor', heightFactor, defaultValue: null));
2034
  }
Hixie's avatar
Hixie committed
2035 2036
}

2037 2038 2039
/// A box that limits its size only when it's unconstrained.
///
/// If this widget's maximum width is unconstrained then its child's width is
Ian Hickson's avatar
Ian Hickson committed
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
/// limited to [maxWidth]. Similarly, if this widget's maximum height is
/// unconstrained then its child's height is limited to [maxHeight].
///
/// This has the effect of giving the child a natural dimension in unbounded
/// environments. For example, by providing a [maxHeight] to a widget that
/// normally tries to be as big as possible, the widget will normally size
/// itself to fit its parent, but when placed in a vertical list, it will take
/// on the given height.
///
/// This is useful when composing widgets that normally try to match their
/// parents' size, so that they behave reasonably in lists (which are
/// unbounded).
2052 2053 2054 2055 2056 2057 2058
///
/// See also:
///
///  * [ConstrainedBox], which applies its constraints in all cases, not just
///    when the incoming constraints are unbounded.
///  * [SizedBox], which lets you specify tight constraints by explicitly
///    specifying the height or width.
2059
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2060
class LimitedBox extends SingleChildRenderObjectWidget {
2061 2062 2063 2064
  /// Creates a box that limits its size only when it's unconstrained.
  ///
  /// The [maxWidth] and [maxHeight] arguments must not be null and must not be
  /// negative.
2065
  const LimitedBox({
2066
    Key key,
2067 2068
    this.maxWidth = double.infinity,
    this.maxHeight = double.infinity,
2069
    Widget child,
2070 2071 2072
  }) : assert(maxWidth != null && maxWidth >= 0.0),
       assert(maxHeight != null && maxHeight >= 0.0),
       super(key: key, child: child);
2073

Ian Hickson's avatar
Ian Hickson committed
2074 2075
  /// The maximum width limit to apply in the absence of a
  /// [BoxConstraints.maxWidth] constraint.
2076 2077
  final double maxWidth;

Ian Hickson's avatar
Ian Hickson committed
2078 2079
  /// The maximum height limit to apply in the absence of a
  /// [BoxConstraints.maxHeight] constraint.
2080 2081 2082
  final double maxHeight;

  @override
2083 2084 2085 2086 2087 2088
  RenderLimitedBox createRenderObject(BuildContext context) {
    return new RenderLimitedBox(
      maxWidth: maxWidth,
      maxHeight: maxHeight
    );
  }
2089 2090 2091 2092 2093 2094 2095 2096 2097

  @override
  void updateRenderObject(BuildContext context, RenderLimitedBox renderObject) {
    renderObject
      ..maxWidth = maxWidth
      ..maxHeight = maxHeight;
  }

  @override
2098 2099 2100 2101
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DoubleProperty('maxWidth', maxWidth, defaultValue: double.infinity));
    properties.add(new DoubleProperty('maxHeight', maxHeight, defaultValue: double.infinity));
2102 2103 2104
  }
}

2105
/// A widget that imposes different constraints on its child than it gets
2106 2107
/// from its parent, possibly allowing the child to overflow the parent.
///
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
/// See also:
///
///  * [RenderConstrainedOverflowBox] for details about how [OverflowBox] is
///    rendered.
///  * [SizedOverflowBox], a widget that is a specific size but passes its
///    original constraints through to its child, which may then overflow.
///  * [ConstrainedBox], a widget that imposes additional constraints on its
///    child.
///  * [UnconstrainedBox], a container that tries to let its child draw without
///    constraints.
///  * [SizedBox], a box with a specified size.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2120
class OverflowBox extends SingleChildRenderObjectWidget {
2121
  /// Creates a widget that lets its child overflow itself.
2122
  const OverflowBox({
2123
    Key key,
2124
    this.alignment = Alignment.center,
2125 2126 2127 2128
    this.minWidth,
    this.maxWidth,
    this.minHeight,
    this.maxHeight,
2129
    Widget child,
2130
  }) : super(key: key, child: child);
2131

2132 2133 2134
  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
2135
  /// alignment, respectively. An x value of -1.0 means that the left edge of
2136 2137 2138
  /// the child is aligned with the left edge of the parent whereas an x value
  /// of 1.0 means that the right edge of the child is aligned with the right
  /// edge of the parent. Other values interpolate (and extrapolate) linearly.
2139
  /// For example, a value of 0.0 means that the center of the child is aligned
2140
  /// with the center of the parent.
2141 2142 2143 2144 2145 2146 2147 2148 2149
  ///
  /// Defaults to [Alignment.center].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
2150
  final AlignmentGeometry alignment;
2151

2152 2153
  /// The minimum width constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
2154
  final double minWidth;
2155 2156 2157

  /// The maximum width constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
2158
  final double maxWidth;
2159 2160 2161

  /// The minimum height constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
2162
  final double minHeight;
2163 2164 2165

  /// The maximum height constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
2166 2167
  final double maxHeight;

2168
  @override
2169 2170 2171 2172 2173 2174
  RenderConstrainedOverflowBox createRenderObject(BuildContext context) {
    return new RenderConstrainedOverflowBox(
      alignment: alignment,
      minWidth: minWidth,
      maxWidth: maxWidth,
      minHeight: minHeight,
2175 2176
      maxHeight: maxHeight,
      textDirection: Directionality.of(context),
2177 2178
    );
  }
2179

2180
  @override
2181
  void updateRenderObject(BuildContext context, RenderConstrainedOverflowBox renderObject) {
2182
    renderObject
2183
      ..alignment = alignment
2184 2185 2186
      ..minWidth = minWidth
      ..maxWidth = maxWidth
      ..minHeight = minHeight
2187 2188
      ..maxHeight = maxHeight
      ..textDirection = Directionality.of(context);
2189
  }
2190

2191
  @override
2192 2193 2194 2195 2196 2197 2198
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(new DoubleProperty('minWidth', minWidth, defaultValue: null));
    properties.add(new DoubleProperty('maxWidth', maxWidth, defaultValue: null));
    properties.add(new DoubleProperty('minHeight', minHeight, defaultValue: null));
    properties.add(new DoubleProperty('maxHeight', maxHeight, defaultValue: null));
2199
  }
2200 2201
}

2202
/// A widget that is a specific size but passes its original constraints
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
/// through to its child, which may then overflow.
///
/// See also:
///
///  * [OverflowBox], A widget that imposes different constraints on its child
///    than it gets from its parent, possibly allowing the child to overflow the
///    parent.
///  * [ConstrainedBox], a widget that imposes additional constraints on its
///    child.
///  * [UnconstrainedBox], a container that tries to let its child draw without
///    constraints.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2215
class SizedOverflowBox extends SingleChildRenderObjectWidget {
2216 2217
  /// Creates a widget of a given size that lets its child overflow.
  ///
2218
  /// The [size] argument must not be null.
2219
  const SizedOverflowBox({
2220
    Key key,
2221
    @required this.size,
2222
    this.alignment = Alignment.center,
2223
    Widget child,
2224 2225 2226
  }) : assert(size != null),
       assert(alignment != null),
       super(key: key, child: child);
2227 2228 2229 2230

  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
2231
  /// alignment, respectively. An x value of -1.0 means that the left edge of
2232 2233 2234
  /// the child is aligned with the left edge of the parent whereas an x value
  /// of 1.0 means that the right edge of the child is aligned with the right
  /// edge of the parent. Other values interpolate (and extrapolate) linearly.
2235
  /// For example, a value of 0.0 means that the center of the child is aligned
2236
  /// with the center of the parent.
2237 2238 2239 2240 2241 2242 2243 2244 2245
  ///
  /// Defaults to [Alignment.center].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
2246
  final AlignmentGeometry alignment;
2247

2248
  /// The size this widget should attempt to be.
2249 2250
  final Size size;

2251
  @override
2252 2253 2254
  RenderSizedOverflowBox createRenderObject(BuildContext context) {
    return new RenderSizedOverflowBox(
      alignment: alignment,
2255 2256
      requestedSize: size,
      textDirection: Directionality.of(context),
2257 2258
    );
  }
2259

2260
  @override
2261
  void updateRenderObject(BuildContext context, RenderSizedOverflowBox renderObject) {
2262 2263
    renderObject
      ..alignment = alignment
2264 2265
      ..requestedSize = size
      ..textDirection = Directionality.of(context);
2266 2267 2268
  }

  @override
2269 2270 2271 2272
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(new DiagnosticsProperty<Size>('size', size, defaultValue: null));
2273 2274 2275
  }
}

2276 2277 2278
/// A widget that lays the child out as if it was in the tree, but without
/// painting anything, without making the child available for hit testing, and
/// without taking any room in the parent.
2279
///
2280 2281 2282 2283 2284 2285 2286 2287
/// Animations continue to run in offstage children, and therefore use battery
/// and CPU time, regardless of whether the animations end up being visible.
///
/// [Offstage] can be used to measure the dimensions of a widget without
/// bringing it on screen (yet). To hide a widget from view while it is not
/// needed, prefer removing the widget from the tree entirely rather than
/// keeping it alive in an [Offstage] subtree.
///
2288 2289
/// See also:
///
2290 2291
///  * [Visibility], which can hide a child more efficiently (albeit less
///    subtly).
2292
///  * [TickerMode], which can be used to disable animations in a subtree.
2293
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2294
class Offstage extends SingleChildRenderObjectWidget {
2295
  /// Creates a widget that visually hides its child.
2296
  const Offstage({ Key key, this.offstage = true, Widget child })
2297 2298
    : assert(offstage != null),
      super(key: key, child: child);
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309

  /// Whether the child is hidden from the rest of the tree.
  ///
  /// If true, the child is laid out as if it was in the tree, but without
  /// painting anything, without making the child available for hit testing, and
  /// without taking any room in the parent.
  ///
  /// If false, the child is included in the tree as normal.
  final bool offstage;

  @override
2310
  RenderOffstage createRenderObject(BuildContext context) => new RenderOffstage(offstage: offstage);
Hixie's avatar
Hixie committed
2311

2312
  @override
2313
  void updateRenderObject(BuildContext context, RenderOffstage renderObject) {
2314 2315 2316 2317
    renderObject.offstage = offstage;
  }

  @override
2318 2319 2320
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<bool>('offstage', offstage));
2321
  }
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

  @override
  _OffstageElement createElement() => new _OffstageElement(this);
}

class _OffstageElement extends SingleChildRenderObjectElement {
  _OffstageElement(Offstage widget) : super(widget);

  @override
  Offstage get widget => super.widget;

  @override
2334
  void debugVisitOnstageChildren(ElementVisitor visitor) {
2335
    if (!widget.offstage)
2336
      super.debugVisitOnstageChildren(visitor);
2337
  }
Hixie's avatar
Hixie committed
2338 2339
}

2340
/// A widget that attempts to size the child to a specific aspect ratio.
2341
///
2342
/// The widget first tries the largest width permitted by the layout
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
/// constraints. The height of the widget is determined by applying the
/// given aspect ratio to the width, expressed as a ratio of width to height.
///
/// For example, a 16:9 width:height aspect ratio would have a value of
/// 16.0/9.0. If the maximum width is infinite, the initial width is determined
/// by applying the aspect ratio to the maximum height.
///
/// Now consider a second example, this time with an aspect ratio of 2.0 and
/// layout constraints that require the width to be between 0.0 and 100.0 and
/// the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the
/// biggest allowed) and a height of 50.0 (to match the aspect ratio).
///
/// In that same situation, if the aspect ratio is 0.5, we'll also select a
/// width of 100.0 (still the biggest allowed) and we'll attempt to use a height
/// of 200.0. Unfortunately, that violates the constraints because the child can
/// be at most 100.0 pixels tall. The widget will then take that value
/// and apply the aspect ratio again to obtain a width of 50.0. That width is
/// permitted by the constraints and the child receives a width of 50.0 and a
/// height of 100.0. If the width were not permitted, the widget would
/// continue iterating through the constraints. If the widget does not
/// find a feasible size after consulting each constraint, the widget
/// will eventually select a size for the child that meets the layout
/// constraints but fails to meet the aspect ratio constraints.
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
///
/// See also:
///
///  * [Align], a widget that aligns its child within itself and optionally
///    sizes itself based on the child's size.
///  * [ConstrainedBox], a widget that imposes additional constraints on its
///    child.
///  * [UnconstrainedBox], a container that tries to let its child draw without
///    constraints.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2376
class AspectRatio extends SingleChildRenderObjectWidget {
2377 2378 2379
  /// Creates a widget with a specific aspect ratio.
  ///
  /// The [aspectRatio] argument must not be null.
2380
  const AspectRatio({
2381 2382 2383
    Key key,
    @required this.aspectRatio,
    Widget child
2384 2385
  }) : assert(aspectRatio != null),
       super(key: key, child: child);
2386

2387
  /// The aspect ratio to attempt to use.
2388 2389 2390
  ///
  /// The aspect ratio is expressed as a ratio of width to height. For example,
  /// a 16:9 width:height aspect ratio would have a value of 16.0/9.0.
2391 2392
  final double aspectRatio;

2393
  @override
2394
  RenderAspectRatio createRenderObject(BuildContext context) => new RenderAspectRatio(aspectRatio: aspectRatio);
2395

2396
  @override
2397
  void updateRenderObject(BuildContext context, RenderAspectRatio renderObject) {
2398
    renderObject.aspectRatio = aspectRatio;
2399
  }
2400

2401
  @override
2402 2403 2404
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DoubleProperty('aspectRatio', aspectRatio));
2405
  }
2406 2407
}

2408
/// A widget that sizes its child to the child's intrinsic width.
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
///
/// Sizes its child's width to the child's maximum intrinsic width. If
/// [stepWidth] is non-null, the child's width will be snapped to a multiple of
/// the [stepWidth]. Similarly, if [stepHeight] is non-null, the child's height
/// will be snapped to a multiple of the [stepHeight].
///
/// This class is useful, for example, when unlimited width is available and
/// you would like a child that would otherwise attempt to expand infinitely to
/// instead size itself to a more reasonable width.
///
2419 2420 2421 2422
/// This class is relatively expensive, because it adds a speculative layout
/// pass before the final layout phase. Avoid using it where possible. In the
/// worst case, this widget can result in a layout that is O(N²) in the depth of
/// the tree.
2423 2424 2425 2426
///
/// See also:
///
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2427
class IntrinsicWidth extends SingleChildRenderObjectWidget {
2428 2429 2430
  /// Creates a widget that sizes its child to the child's intrinsic width.
  ///
  /// This class is relatively expensive. Avoid using it where possible.
2431
  const IntrinsicWidth({ Key key, this.stepWidth, this.stepHeight, Widget child })
2432 2433
    : super(key: key, child: child);

2434
  /// If non-null, force the child's width to be a multiple of this value.
2435
  final double stepWidth;
2436 2437

  /// If non-null, force the child's height to be a multiple of this value.
2438 2439
  final double stepHeight;

2440
  @override
2441 2442 2443
  RenderIntrinsicWidth createRenderObject(BuildContext context) {
    return new RenderIntrinsicWidth(stepWidth: stepWidth, stepHeight: stepHeight);
  }
2444

2445
  @override
2446
  void updateRenderObject(BuildContext context, RenderIntrinsicWidth renderObject) {
2447 2448 2449
    renderObject
      ..stepWidth = stepWidth
      ..stepHeight = stepHeight;
2450 2451 2452
  }
}

2453
/// A widget that sizes its child to the child's intrinsic height.
2454 2455 2456 2457 2458
///
/// This class is useful, for example, when unlimited height is available and
/// you would like a child that would otherwise attempt to expand infinitely to
/// instead size itself to a more reasonable height.
///
2459 2460 2461 2462
/// This class is relatively expensive, because it adds a speculative layout
/// pass before the final layout phase. Avoid using it where possible. In the
/// worst case, this widget can result in a layout that is O(N²) in the depth of
/// the tree.
2463 2464 2465 2466
///
/// See also:
///
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2467
class IntrinsicHeight extends SingleChildRenderObjectWidget {
2468 2469 2470
  /// Creates a widget that sizes its child to the child's intrinsic height.
  ///
  /// This class is relatively expensive. Avoid using it where possible.
2471
  const IntrinsicHeight({ Key key, Widget child }) : super(key: key, child: child);
2472 2473

  @override
2474
  RenderIntrinsicHeight createRenderObject(BuildContext context) => new RenderIntrinsicHeight();
Hixie's avatar
Hixie committed
2475 2476
}

2477 2478 2479
/// A widget that positions its child according to the child's baseline.
///
/// This widget shifts the child down such that the child's baseline (or the
2480 2481 2482 2483 2484
/// bottom of the child, if the child has no baseline) is [baseline]
/// logical pixels below the top of this box, then sizes this box to
/// contain the child. If [baseline] is less than the distance from
/// the top of the child to the baseline of the child, then the child
/// is top-aligned instead.
2485 2486 2487 2488 2489 2490 2491
///
/// See also:
///
///  * [Align], a widget that aligns its child within itself and optionally
///    sizes itself based on the child's size.
///  * [Center], a widget that centers its child within itself.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2492
class Baseline extends SingleChildRenderObjectWidget {
2493
  /// Creates a widget that positions its child according to the child's baseline.
2494
  ///
2495
  /// The [baseline] and [baselineType] arguments must not be null.
2496
  const Baseline({
2497 2498 2499 2500
    Key key,
    @required this.baseline,
    @required this.baselineType,
    Widget child
2501 2502 2503
  }) : assert(baseline != null),
       assert(baselineType != null),
       super(key: key, child: child);
2504

2505 2506 2507 2508 2509
  /// The number of logical pixels from the top of this box at which to position
  /// the child's baseline.
  final double baseline;

  /// The type of baseline to use for positioning the child.
2510 2511
  final TextBaseline baselineType;

2512
  @override
2513 2514 2515
  RenderBaseline createRenderObject(BuildContext context) {
    return new RenderBaseline(baseline: baseline, baselineType: baselineType);
  }
2516

2517
  @override
2518
  void updateRenderObject(BuildContext context, RenderBaseline renderObject) {
2519 2520 2521
    renderObject
      ..baseline = baseline
      ..baselineType = baselineType;
2522 2523 2524 2525
  }
}


Ian Hickson's avatar
Ian Hickson committed
2526 2527
// SLIVERS

2528 2529 2530 2531 2532 2533 2534 2535 2536
/// A sliver that contains a single box widget.
///
/// Slivers are special-purpose widgets that can be combined using a
/// [CustomScrollView] to create custom scroll effects. A [SliverToBoxAdapter]
/// is a basic sliver that creates a bridge back to one of the usual box-based
/// widgets.
///
/// Rather than using multiple [SliverToBoxAdapter] widgets to display multiple
/// box widgets in a [CustomScrollView], consider using [SliverList],
2537 2538 2539
/// [SliverFixedExtentList], [SliverPrototypeExtentList], or [SliverGrid],
/// which are more efficient because they instantiate only those children that
/// are actually visible through the scroll view's viewport.
2540 2541 2542 2543 2544 2545 2546
///
/// See also:
///
///  * [CustomScrollView], which displays a scrollable list of slivers.
///  * [SliverList], which displays multiple box widgets in a linear array.
///  * [SliverFixedExtentList], which displays multiple box widgets with the
///    same main-axis extent in a linear array.
2547 2548
///  * [SliverPrototypeExtentList], which displays multiple box widgets with the
///    same main-axis extent as a prototype item, in a linear array.
2549
///  * [SliverGrid], which displays multiple box widgets in arbitrary positions.
Ian Hickson's avatar
Ian Hickson committed
2550
class SliverToBoxAdapter extends SingleChildRenderObjectWidget {
2551
  /// Creates a sliver that contains a single box widget.
2552
  const SliverToBoxAdapter({
Ian Hickson's avatar
Ian Hickson committed
2553 2554 2555 2556 2557 2558 2559 2560
    Key key,
    Widget child,
  }) : super(key: key, child: child);

  @override
  RenderSliverToBoxAdapter createRenderObject(BuildContext context) => new RenderSliverToBoxAdapter();
}

2561 2562 2563 2564 2565 2566 2567 2568
/// A sliver that applies padding on each side of another sliver.
///
/// Slivers are special-purpose widgets that can be combined using a
/// [CustomScrollView] to create custom scroll effects. A [SliverPadding]
/// is a basic sliver that insets another sliver by applying padding on each
/// side.
///
/// Applying padding to anything but the most mundane sliver is likely to have
2569 2570 2571 2572
/// undesired effects. For example, wrapping a [SliverPersistentHeader] with
/// `pinned:true` will cause the app bar to overlap earlier slivers (contrary to
/// the normal behavior of pinned app bars), and while the app bar is pinned,
/// the padding will scroll away.
2573 2574 2575 2576
///
/// See also:
///
///  * [CustomScrollView], which displays a scrollable list of slivers.
Ian Hickson's avatar
Ian Hickson committed
2577
class SliverPadding extends SingleChildRenderObjectWidget {
2578 2579 2580
  /// Creates a sliver that applies padding on each side of another sliver.
  ///
  /// The [padding] argument must not be null.
2581
  const SliverPadding({
Ian Hickson's avatar
Ian Hickson committed
2582 2583
    Key key,
    @required this.padding,
2584
    Widget sliver,
2585 2586
  }) : assert(padding != null),
       super(key: key, child: sliver);
Ian Hickson's avatar
Ian Hickson committed
2587

2588
  /// The amount of space by which to inset the child sliver.
2589
  final EdgeInsetsGeometry padding;
2590

Ian Hickson's avatar
Ian Hickson committed
2591
  @override
2592 2593 2594 2595 2596 2597
  RenderSliverPadding createRenderObject(BuildContext context) {
    return new RenderSliverPadding(
      padding: padding,
      textDirection: Directionality.of(context),
    );
  }
Ian Hickson's avatar
Ian Hickson committed
2598 2599 2600

  @override
  void updateRenderObject(BuildContext context, RenderSliverPadding renderObject) {
2601 2602 2603
    renderObject
      ..padding = padding
      ..textDirection = Directionality.of(context);
Ian Hickson's avatar
Ian Hickson committed
2604 2605 2606
  }

  @override
2607 2608 2609
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
Ian Hickson's avatar
Ian Hickson committed
2610 2611 2612 2613
  }
}


2614 2615
// LAYOUT NODES

2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
/// Returns the [AxisDirection] in the given [Axis] in the current
/// [Directionality] (or the reverse if `reverse` is true).
///
/// If `axis` is [Axis.vertical], this function returns [AxisDirection.down]
/// unless `reverse` is true, in which case this function returns
/// [AxisDirection.up].
///
/// If `axis` is [Axis.horizontal], this function checks the current
/// [Directionality]. If the current [Directionality] is right-to-left, then
/// this function returns [AxisDirection.left] (unless `reverse` is true, in
/// which case it returns [AxisDirection.right]). Similarly, if the current
/// [Directionality] is left-to-right, then this function returns
/// [AxisDirection.right] (unless `reverse` is true, in which case it returns
/// [AxisDirection.left]).
///
/// This function is used by a number of scrolling widgets (e.g., [ListView],
/// [GridView], [PageView], and [SingleChildScrollView]) as well as [ListBody]
/// to translate their [Axis] and `reverse` properties into a concrete
/// [AxisDirection].
AxisDirection getAxisDirectionFromAxisReverseAndDirectionality(
  BuildContext context,
  Axis axis,
  bool reverse,
) {
  switch (axis) {
    case Axis.horizontal:
      assert(debugCheckHasDirectionality(context));
      final TextDirection textDirection = Directionality.of(context);
      final AxisDirection axisDirection = textDirectionToAxisDirection(textDirection);
      return reverse ? flipAxisDirection(axisDirection) : axisDirection;
    case Axis.vertical:
      return reverse ? AxisDirection.up : AxisDirection.down;
  }
  return null;
}

2652 2653
/// A widget that arranges its children sequentially along a given axis, forcing
/// them to the dimension of the parent in the other axis.
2654
///
2655
/// This widget is rarely used directly. Instead, consider using [ListView],
2656 2657 2658
/// which combines a similar layout algorithm with scrolling behavior, or
/// [Column], which gives you more flexible control over the layout of a
/// vertical set of boxes.
2659
///
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
/// See also:
///
///  * [RenderListBody], which implements this layout algorithm and the
///    documentation for which describes some of its subtleties.
///  * [SingleChildScrollView], which is sometimes used with [ListBody] to
///    make the contents scrollable.
///  * [Column] and [Row], which implement a more elaborate version of
///    this layout algorithm (at the cost of being slightly less efficient).
///  * [ListView], which implements an efficient scrolling version of this
///    layout algorithm.
class ListBody extends MultiChildRenderObjectWidget {
  /// Creates a layout widget that arranges its children sequentially along a
  /// given axis.
2673 2674
  ///
  /// By default, the [mainAxis] is [Axis.vertical].
2675
  ListBody({
2676
    Key key,
2677 2678 2679
    this.mainAxis = Axis.vertical,
    this.reverse = false,
    List<Widget> children = const <Widget>[],
2680 2681
  }) : assert(mainAxis != null),
       super(key: key, children: children);
2682

2683
  /// The direction to use as the main axis.
2684
  final Axis mainAxis;
2685

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
  /// Whether the list body positions children in the reading direction.
  ///
  /// For example, if the reading direction is left-to-right and
  /// [mainAxis] is [Axis.horizontal], then the list body positions children
  /// from left to right when [reverse] is false and from right to left when
  /// [reverse] is true.
  ///
  /// Similarly, if [mainAxis] is [Axis.vertical], then the list body positions
  /// from top to bottom when [reverse] is false and from bottom to top when
  /// [reverse] is true.
  ///
  /// Defaults to false.
  final bool reverse;

  AxisDirection _getDirection(BuildContext context) {
    return getAxisDirectionFromAxisReverseAndDirectionality(context, mainAxis, reverse);
  }

2704
  @override
2705 2706 2707
  RenderListBody createRenderObject(BuildContext context) {
    return new RenderListBody(axisDirection: _getDirection(context));
  }
2708

2709
  @override
2710
  void updateRenderObject(BuildContext context, RenderListBody renderObject) {
2711
    renderObject.axisDirection = _getDirection(context);
2712
  }
2713 2714
}

Ian Hickson's avatar
Ian Hickson committed
2715
/// A widget that positions its children relative to the edges of its box.
Adam Barth's avatar
Adam Barth committed
2716
///
2717 2718 2719
/// This class is useful if you want to overlap several children in a simple
/// way, for example having some text and an image, overlaid with a gradient and
/// a button attached to the bottom.
2720
///
2721 2722 2723 2724
/// Each child of a [Stack] widget is either _positioned_ or _non-positioned_.
/// Positioned children are those wrapped in a [Positioned] widget that has at
/// least one non-null property. The stack sizes itself to contain all the
/// non-positioned children, which are positioned according to [alignment]
2725 2726 2727 2728
/// (which defaults to the top-left corner in left-to-right environments and the
/// top-right corner in right-to-left environments). The positioned children are
/// then placed relative to the stack according to their top, right, bottom, and
/// left properties.
2729
///
2730 2731 2732 2733 2734 2735 2736
/// The stack paints its children in order with the first child being at the
/// bottom. If you want to change the order in which the children paint, you
/// can rebuild the stack with the children in the new order. If you reorder
/// the children in this way, consider giving the children non-null keys.
/// These keys will cause the framework to move the underlying objects for
/// the children to their new locations rather than recreate them at their
/// new location.
2737
///
2738 2739 2740 2741 2742 2743
/// For more details about the stack layout algorithm, see [RenderStack].
///
/// If you want to lay a number of children out in a particular pattern, or if
/// you want to make a custom layout manager, you probably want to use
/// [CustomMultiChildLayout] instead. In particular, when using a [Stack] you
/// can't position children relative to their size or the stack's own size.
Adam Barth's avatar
Adam Barth committed
2744 2745 2746
///
/// See also:
///
2747
///  * [Align], which sizes itself based on its child's size and positions
2748
///    the child according to an [Alignment] value.
2749 2750 2751 2752 2753 2754
///  * [CustomSingleChildLayout], which uses a delegate to control the layout of
///    a single child.
///  * [CustomMultiChildLayout], which uses a delegate to position multiple
///    children.
///  * [Flow], which provides paint-time control of its children using transform
///    matrices.
2755
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2756
class Stack extends MultiChildRenderObjectWidget {
2757
  /// Creates a stack layout widget.
2758 2759 2760
  ///
  /// By default, the non-positioned children of the stack are aligned by their
  /// top left corners.
2761
  Stack({
Hans Muller's avatar
Hans Muller committed
2762
    Key key,
2763
    this.alignment = AlignmentDirectional.topStart,
2764
    this.textDirection,
2765 2766 2767
    this.fit = StackFit.loose,
    this.overflow = Overflow.clip,
    List<Widget> children = const <Widget>[],
2768
  }) : super(key: key, children: children);
Hans Muller's avatar
Hans Muller committed
2769

2770 2771
  /// How to align the non-positioned and partially-positioned children in the
  /// stack.
2772 2773 2774
  ///
  /// The non-positioned children are placed relative to each other such that
  /// the points determined by [alignment] are co-located. For example, if the
2775
  /// [alignment] is [Alignment.topLeft], then the top left corner of
2776
  /// each non-positioned child will be located at the same global coordinate.
2777 2778 2779 2780 2781
  ///
  /// Partially-positioned children, those that do not specify an alignment in a
  /// particular axis (e.g. that have neither `top` nor `bottom` set), use the
  /// alignment to determine how they should be positioned in that
  /// under-specified axis.
2782 2783 2784 2785 2786 2787 2788 2789 2790
  ///
  /// Defaults to [AlignmentDirectional.topStart].
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
2791
  final AlignmentGeometry alignment;
2792 2793 2794 2795 2796

  /// The text direction with which to resolve [alignment].
  ///
  /// Defaults to the ambient [Directionality].
  final TextDirection textDirection;
Hans Muller's avatar
Hans Muller committed
2797

2798 2799 2800 2801 2802
  /// How to size the non-positioned children in the stack.
  ///
  /// The constraints passed into the [Stack] from its parent are either
  /// loosened ([StackFit.loose]) or tightened to their biggest size
  /// ([StackFit.expand]).
2803
  final StackFit fit;
2804

2805 2806 2807
  /// Whether overflowing children should be clipped. See [Overflow].
  ///
  /// Some children in a stack might overflow its box. When this flag is set to
2808
  /// [Overflow.clip], children cannot paint outside of the stack's box.
2809 2810
  final Overflow overflow;

2811
  @override
2812 2813 2814
  RenderStack createRenderObject(BuildContext context) {
    return new RenderStack(
      alignment: alignment,
2815
      textDirection: textDirection ?? Directionality.of(context),
2816
      fit: fit,
2817
      overflow: overflow,
2818 2819
    );
  }
Hans Muller's avatar
Hans Muller committed
2820

2821
  @override
2822
  void updateRenderObject(BuildContext context, RenderStack renderObject) {
2823 2824
    renderObject
      ..alignment = alignment
2825
      ..textDirection = textDirection ?? Directionality.of(context)
2826
      ..fit = fit
2827
      ..overflow = overflow;
Hans Muller's avatar
Hans Muller committed
2828
  }
2829 2830

  @override
2831 2832 2833 2834 2835 2836
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(new EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
    properties.add(new EnumProperty<StackFit>('fit', fit));
    properties.add(new EnumProperty<Overflow>('overflow', overflow));
2837
  }
Hans Muller's avatar
Hans Muller committed
2838 2839
}

2840
/// A [Stack] that shows a single child from a list of children.
2841
///
2842 2843 2844 2845
/// The displayed child is the one with the given [index]. The stack is
/// always as big as the largest child.
///
/// If value is null, then nothing is displayed.
2846
///
2847 2848 2849 2850
/// See also:
///
///  * [Stack], for more details about stacks.
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
2851
class IndexedStack extends Stack {
2852
  /// Creates a [Stack] widget that paints a single child.
2853 2854
  ///
  /// The [index] argument must not be null.
2855
  IndexedStack({
Hans Muller's avatar
Hans Muller committed
2856
    Key key,
2857
    AlignmentGeometry alignment = AlignmentDirectional.topStart,
2858
    TextDirection textDirection,
2859 2860 2861
    StackFit sizing = StackFit.loose,
    this.index = 0,
    List<Widget> children = const <Widget>[],
2862
  }) : super(key: key, alignment: alignment, textDirection: textDirection, fit: sizing, children: children);
Hans Muller's avatar
Hans Muller committed
2863

Adam Barth's avatar
Adam Barth committed
2864
  /// The index of the child to show.
Hans Muller's avatar
Hans Muller committed
2865
  final int index;
Adam Barth's avatar
Adam Barth committed
2866

2867
  @override
2868 2869 2870 2871 2872 2873 2874
  RenderIndexedStack createRenderObject(BuildContext context) {
    return new RenderIndexedStack(
      index: index,
      alignment: alignment,
      textDirection: textDirection ?? Directionality.of(context),
    );
  }
Hans Muller's avatar
Hans Muller committed
2875

2876
  @override
2877
  void updateRenderObject(BuildContext context, RenderIndexedStack renderObject) {
2878 2879
    renderObject
      ..index = index
2880 2881
      ..alignment = alignment
      ..textDirection = textDirection ?? Directionality.of(context);
Hans Muller's avatar
Hans Muller committed
2882
  }
2883 2884
}

2885
/// A widget that controls where a child of a [Stack] is positioned.
Adam Barth's avatar
Adam Barth committed
2886
///
2887 2888 2889 2890
/// A [Positioned] widget must be a descendant of a [Stack], and the path from
/// the [Positioned] widget to its enclosing [Stack] must contain only
/// [StatelessWidget]s or [StatefulWidget]s (not other kinds of widgets, like
/// [RenderObjectWidget]s).
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
///
/// If a widget is wrapped in a [Positioned], then it is a _positioned_ widget
/// in its [Stack]. If the [top] property is non-null, the top edge of this child
/// will be positioned [top] layout units from the top of the stack widget. The
/// [right], [bottom], and [left] properties work analogously.
///
/// If both the [top] and [bottom] properties are non-null, then the child will
/// be forced to have exactly the height required to satisfy both constraints.
/// Similarly, setting the [right] and [left] properties to non-null values will
/// force the child to have a particular width. Alternatively the [width] and
/// [height] properties can be used to give the dimensions, with one
/// corresponding position property (e.g. [top] and [height]).
2903
///
2904 2905 2906 2907 2908 2909
/// If all three values on a particular axis are null, then the
/// [Stack.alignment] property is used to position the child.
///
/// If all six values are null, the child is a non-positioned child. The [Stack]
/// uses only the non-positioned children to size itself.
///
2910 2911 2912
/// See also:
///
///  * [PositionedDirectional], which adapts to the ambient [Directionality].
2913
class Positioned extends ParentDataWidget<Stack> {
2914
  /// Creates a widget that controls where a child of a [Stack] is positioned.
Hixie's avatar
Hixie committed
2915 2916 2917 2918 2919
  ///
  /// Only two out of the three horizontal values ([left], [right],
  /// [width]), and only two out of the three vertical values ([top],
  /// [bottom], [height]), can be set. In each case, at least one of
  /// the three must be null.
2920 2921 2922 2923
  ///
  /// See also:
  ///
  ///  * [Positioned.directional], which specifies the widget's horizontal
2924
  ///    position using `start` and `end` rather than `left` and `right`.
2925 2926
  ///  * [PositionedDirectional], which is similar to [Positioned.directional]
  ///    but adapts to the ambient [Directionality].
2927
  const Positioned({
2928
    Key key,
2929
    this.left,
2930 2931 2932
    this.top,
    this.right,
    this.bottom,
2933
    this.width,
2934
    this.height,
2935
    @required Widget child,
2936 2937 2938
  }) : assert(left == null || right == null || width == null),
       assert(top == null || bottom == null || height == null),
       super(key: key, child: child);
2939

Hixie's avatar
Hixie committed
2940 2941 2942 2943 2944
  /// Creates a Positioned object with the values from the given [Rect].
  ///
  /// This sets the [left], [top], [width], and [height] properties
  /// from the given [Rect]. The [right] and [bottom] properties are
  /// set to null.
2945 2946
  Positioned.fromRect({
    Key key,
2947 2948
    Rect rect,
    @required Widget child,
2949 2950 2951 2952
  }) : left = rect.left,
       top = rect.top,
       width = rect.width,
       height = rect.height,
2953 2954
       right = null,
       bottom = null,
2955
       super(key: key, child: child);
2956

2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
  /// Creates a Positioned object with the values from the given [RelativeRect].
  ///
  /// This sets the [left], [top], [right], and [bottom] properties from the
  /// given [RelativeRect]. The [height] and [width] properties are set to null.
  Positioned.fromRelativeRect({
    Key key,
    RelativeRect rect,
    @required Widget child,
  }) : left = rect.left,
       top = rect.top,
       right = rect.right,
       bottom = rect.bottom,
       width = null,
       height = null,
       super(key: key, child: child);

2973 2974
  /// Creates a Positioned object with [left], [top], [right], and [bottom] set
  /// to 0.0 unless a value for them is passed.
2975
  const Positioned.fill({
2976
    Key key,
2977 2978 2979 2980
    this.left = 0.0,
    this.top = 0.0,
    this.right = 0.0,
    this.bottom = 0.0,
2981
    @required Widget child,
2982 2983 2984 2985
  }) : width = null,
       height = null,
       super(key: key, child: child);

2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
  /// Creates a widget that controls where a child of a [Stack] is positioned.
  ///
  /// Only two out of the three horizontal values (`start`, `end`,
  /// [width]), and only two out of the three vertical values ([top],
  /// [bottom], [height]), can be set. In each case, at least one of
  /// the three must be null.
  ///
  /// If `textDirection` is [TextDirection.rtl], then the `start` argument is
  /// used for the [right] property and the `end` argument is used for the
  /// [left] property. Otherwise, if `textDirection` is [TextDirection.ltr],
  /// then the `start` argument is used for the [left] property and the `end`
  /// argument is used for the [right] property.
  ///
  /// The `textDirection` argument must not be null.
  ///
  /// See also:
  ///
  ///  * [PositionedDirectional], which adapts to the ambient [Directionality].
  factory Positioned.directional({
    Key key,
    @required TextDirection textDirection,
    double start,
    double top,
    double end,
    double bottom,
    double width,
    double height,
    @required Widget child,
  }) {
    assert(textDirection != null);
    double left;
    double right;
    switch (textDirection) {
      case TextDirection.rtl:
        left = end;
        right = start;
        break;
      case TextDirection.ltr:
        left = start;
        right = end;
        break;
    }
    return new Positioned(
      key: key,
      left: left,
      top: top,
      right: right,
      bottom: bottom,
      width: width,
      height: height,
      child: child,
    );
  }

Hixie's avatar
Hixie committed
3040 3041 3042 3043
  /// The distance that the child's left edge is inset from the left of the stack.
  ///
  /// Only two out of the three horizontal values ([left], [right], [width]) can be
  /// set. The third must be null.
3044 3045 3046
  ///
  /// If all three are null, the [Stack.alignment] is used to position the child
  /// horizontally.
3047 3048
  final double left;

Hixie's avatar
Hixie committed
3049 3050 3051 3052
  /// The distance that the child's top edge is inset from the top of the stack.
  ///
  /// Only two out of the three vertical values ([top], [bottom], [height]) can be
  /// set. The third must be null.
3053 3054 3055
  ///
  /// If all three are null, the [Stack.alignment] is used to position the child
  /// vertically.
3056
  final double top;
Adam Barth's avatar
Adam Barth committed
3057

Hixie's avatar
Hixie committed
3058 3059 3060 3061
  /// The distance that the child's right edge is inset from the right of the stack.
  ///
  /// Only two out of the three horizontal values ([left], [right], [width]) can be
  /// set. The third must be null.
3062 3063 3064
  ///
  /// If all three are null, the [Stack.alignment] is used to position the child
  /// horizontally.
3065
  final double right;
Adam Barth's avatar
Adam Barth committed
3066

Hixie's avatar
Hixie committed
3067 3068 3069 3070
  /// The distance that the child's bottom edge is inset from the bottom of the stack.
  ///
  /// Only two out of the three vertical values ([top], [bottom], [height]) can be
  /// set. The third must be null.
3071 3072 3073
  ///
  /// If all three are null, the [Stack.alignment] is used to position the child
  /// vertically.
3074
  final double bottom;
Adam Barth's avatar
Adam Barth committed
3075 3076 3077

  /// The child's width.
  ///
Hixie's avatar
Hixie committed
3078
  /// Only two out of the three horizontal values ([left], [right], [width]) can be
3079
  /// set. The third must be null.
3080 3081 3082
  ///
  /// If all three are null, the [Stack.alignment] is used to position the child
  /// horizontally.
3083
  final double width;
Adam Barth's avatar
Adam Barth committed
3084 3085 3086

  /// The child's height.
  ///
Hixie's avatar
Hixie committed
3087
  /// Only two out of the three vertical values ([top], [bottom], [height]) can be
3088
  /// set. The third must be null.
3089 3090 3091
  ///
  /// If all three are null, the [Stack.alignment] is used to position the child
  /// vertically.
3092 3093
  final double height;

3094
  @override
3095 3096 3097
  void applyParentData(RenderObject renderObject) {
    assert(renderObject.parentData is StackParentData);
    final StackParentData parentData = renderObject.parentData;
3098
    bool needsLayout = false;
3099

3100 3101 3102 3103 3104
    if (parentData.left != left) {
      parentData.left = left;
      needsLayout = true;
    }

3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
    if (parentData.top != top) {
      parentData.top = top;
      needsLayout = true;
    }

    if (parentData.right != right) {
      parentData.right = right;
      needsLayout = true;
    }

    if (parentData.bottom != bottom) {
      parentData.bottom = bottom;
      needsLayout = true;
    }

3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
    if (parentData.width != width) {
      parentData.width = width;
      needsLayout = true;
    }

    if (parentData.height != height) {
      parentData.height = height;
      needsLayout = true;
    }

3130
    if (needsLayout) {
3131
      final AbstractNode targetParent = renderObject.parent;
3132 3133 3134
      if (targetParent is RenderObject)
        targetParent.markNeedsLayout();
    }
3135
  }
3136

3137
  @override
3138 3139 3140 3141 3142 3143 3144 3145
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DoubleProperty('left', left, defaultValue: null));
    properties.add(new DoubleProperty('top', top, defaultValue: null));
    properties.add(new DoubleProperty('right', right, defaultValue: null));
    properties.add(new DoubleProperty('bottom', bottom, defaultValue: null));
    properties.add(new DoubleProperty('width', width, defaultValue: null));
    properties.add(new DoubleProperty('height', height, defaultValue: null));
3146
  }
3147 3148
}

3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239
/// A widget that controls where a child of a [Stack] is positioned without
/// committing to a specific [TextDirection].
///
/// The ambient [Directionality] is used to determine whether [start] is to the
/// left or to the right.
///
/// A [PositionedDirectional] widget must be a descendant of a [Stack], and the
/// path from the [PositionedDirectional] widget to its enclosing [Stack] must
/// contain only [StatelessWidget]s or [StatefulWidget]s (not other kinds of
/// widgets, like [RenderObjectWidget]s).
///
/// If a widget is wrapped in a [PositionedDirectional], then it is a
/// _positioned_ widget in its [Stack]. If the [top] property is non-null, the
/// top edge of this child/ will be positioned [top] layout units from the top
/// of the stack widget. The [start], [bottom], and [end] properties work
/// analogously.
///
/// If both the [top] and [bottom] properties are non-null, then the child will
/// be forced to have exactly the height required to satisfy both constraints.
/// Similarly, setting the [start] and [end] properties to non-null values will
/// force the child to have a particular width. Alternatively the [width] and
/// [height] properties can be used to give the dimensions, with one
/// corresponding position property (e.g. [top] and [height]).
///
/// See also:
///
///  * [Positioned], which specifies the widget's position visually.
///  * [Positioned.directional], which also specifies the widget's horizontal
///    position using [start] and [end] but has an explicit [TextDirection].
class PositionedDirectional extends StatelessWidget {
  /// Creates a widget that controls where a child of a [Stack] is positioned.
  ///
  /// Only two out of the three horizontal values (`start`, `end`,
  /// [width]), and only two out of the three vertical values ([top],
  /// [bottom], [height]), can be set. In each case, at least one of
  /// the three must be null.
  ///
  /// See also:
  ///
  ///  * [Positioned.directional], which also specifies the widget's horizontal
  ///    position using [start] and [end] but has an explicit [TextDirection].
  const PositionedDirectional({
    Key key,
    this.start,
    this.top,
    this.end,
    this.bottom,
    this.width,
    this.height,
    @required this.child,
  }) : super(key: key);

  /// The distance that the child's leading edge is inset from the leading edge
  /// of the stack.
  ///
  /// Only two out of the three horizontal values ([start], [end], [width]) can be
  /// set. The third must be null.
  final double start;

  /// The distance that the child's top edge is inset from the top of the stack.
  ///
  /// Only two out of the three vertical values ([top], [bottom], [height]) can be
  /// set. The third must be null.
  final double top;

  /// The distance that the child's trailing edge is inset from the trailing
  /// edge of the stack.
  ///
  /// Only two out of the three horizontal values ([start], [end], [width]) can be
  /// set. The third must be null.
  final double end;

  /// The distance that the child's bottom edge is inset from the bottom of the stack.
  ///
  /// Only two out of the three vertical values ([top], [bottom], [height]) can be
  /// set. The third must be null.
  final double bottom;

  /// The child's width.
  ///
  /// Only two out of the three horizontal values ([start], [end], [width]) can be
  /// set. The third must be null.
  final double width;

  /// The child's height.
  ///
  /// Only two out of the three vertical values ([top], [bottom], [height]) can be
  /// set. The third must be null.
  final double height;

  /// The widget below this widget in the tree.
3240 3241
  ///
  /// {@macro flutter.widgets.child}
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return new Positioned.directional(
      textDirection: Directionality.of(context),
      start: start,
      top: top,
      end: end,
      bottom: bottom,
      width: width,
      height: height,
      child: child,
    );
  }
}

3259
/// A widget that displays its children in a one-dimensional array.
Adam Barth's avatar
Adam Barth committed
3260
///
3261 3262 3263
/// The [Flex] widget allows you to control the axis along which the children are
/// placed (horizontal or vertical). This is referred to as the _main axis_. If
/// you know the main axis in advance, then consider using a [Row] (if it's
3264
/// horizontal) or [Column] (if it's vertical) instead, because that will be less
3265 3266
/// verbose.
///
3267 3268
/// To cause a child to expand to fill the available vertical space, wrap the
/// child in an [Expanded] widget.
3269 3270 3271 3272
///
/// The [Flex] widget does not scroll (and in general it is considered an error
/// to have more children in a [Flex] than will fit in the available room). If
/// you have some widgets and want them to be able to scroll if there is
3273
/// insufficient room, consider using a [ListView].
3274 3275 3276
///
/// If you only have one child, then rather than using [Flex], [Row], or
/// [Column], consider using [Align] or [Center] to position the child.
3277 3278 3279
///
/// ## Layout algorithm
///
3280
/// _This section describes how a [Flex] is rendered by the framework._
3281
/// _See [BoxConstraints] for an introduction to box layout models._
3282
///
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
/// Layout for a [Flex] proceeds in six steps:
///
/// 1. Layout each child a null or zero flex factor (e.g., those that are not
///    [Expanded]) with unbounded main axis constraints and the incoming
///    cross axis constraints. If the [crossAxisAlignment] is
///    [CrossAxisAlignment.stretch], instead use tight cross axis constraints
///    that match the incoming max extent in the cross axis.
/// 2. Divide the remaining main axis space among the children with non-zero
///    flex factors (e.g., those that are [Expanded]) according to their flex
///    factor. For example, a child with a flex factor of 2.0 will receive twice
///    the amount of main axis space as a child with a flex factor of 1.0.
/// 3. Layout each of the remaining children with the same cross axis
///    constraints as in step 1, but instead of using unbounded main axis
///    constraints, use max axis constraints based on the amount of space
///    allocated in step 2. Children with [Flexible.fit] properties that are
///    [FlexFit.tight] are given tight constraints (i.e., forced to fill the
///    allocated space), and children with [Flexible.fit] properties that are
///    [FlexFit.loose] are given loose constraints (i.e., not forced to fill the
///    allocated space).
/// 4. The cross axis extent of the [Flex] is the maximum cross axis extent of
///    the children (which will always satisfy the incoming constraints).
/// 5. The main axis extent of the [Flex] is determined by the [mainAxisSize]
///    property. If the [mainAxisSize] property is [MainAxisSize.max], then the
///    main axis extent of the [Flex] is the max extent of the incoming main
///    axis constraints. If the [mainAxisSize] property is [MainAxisSize.min],
///    then the main axis extent of the [Flex] is the sum of the main axis
///    extents of the children (subject to the incoming constraints).
/// 6. Determine the position for each child according to the
///    [mainAxisAlignment] and the [crossAxisAlignment]. For example, if the
///    [mainAxisAlignment] is [MainAxisAlignment.spaceBetween], any main axis
///    space that has not been allocated to children is divided evenly and
///    placed between the children.
3315 3316 3317 3318 3319 3320 3321
///
/// See also:
///
///  * [Row], for a version of this widget that is always horizontal.
///  * [Column], for a version of this widget that is always vertical.
///  * [Expanded], to indicate children that should take all the remaining room.
///  * [Flexible], to indicate children that should share the remaining room but
3322
///  * [Spacer], a widget that takes up space proportional to it's flex value.
3323
///    that may be sized smaller (leaving some remaining room unused).
3324
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
3325
class Flex extends MultiChildRenderObjectWidget {
3326 3327
  /// Creates a flex layout.
  ///
3328 3329
  /// The [direction] is required.
  ///
3330 3331
  /// The [direction], [mainAxisAlignment], [crossAxisAlignment], and
  /// [verticalDirection] arguments must not be null. If [crossAxisAlignment] is
3332
  /// [CrossAxisAlignment.baseline], then [textBaseline] must not be null.
3333 3334 3335 3336 3337 3338
  ///
  /// The [textDirection] argument defaults to the ambient [Directionality], if
  /// any. If there is no ambient directionality, and a text direction is going
  /// to be necessary to decide which direction to lay the children in or to
  /// disambiguate `start` or `end` values for the main or cross axis
  /// directions, the [textDirection] must not be null.
3339
  Flex({
3340
    Key key,
3341
    @required this.direction,
3342 3343 3344
    this.mainAxisAlignment = MainAxisAlignment.start,
    this.mainAxisSize = MainAxisSize.max,
    this.crossAxisAlignment = CrossAxisAlignment.center,
3345
    this.textDirection,
3346
    this.verticalDirection = VerticalDirection.down,
3347
    this.textBaseline,
3348
    List<Widget> children = const <Widget>[],
3349 3350 3351 3352
  }) : assert(direction != null),
       assert(mainAxisAlignment != null),
       assert(mainAxisSize != null),
       assert(crossAxisAlignment != null),
3353 3354
       assert(verticalDirection != null),
       assert(crossAxisAlignment != CrossAxisAlignment.baseline || textBaseline != null),
3355
       super(key: key, children: children);
3356

3357
  /// The direction to use as the main axis.
3358 3359 3360 3361 3362
  ///
  /// If you know the axis in advance, then consider using a [Row] (if it's
  /// horizontal) or [Column] (if it's vertical) instead of a [Flex], since that
  /// will be less verbose. (For [Row] and [Column] this property is fixed to
  /// the appropriate axis.)
3363
  final Axis direction;
3364 3365

  /// How the children should be placed along the main axis.
3366 3367 3368 3369
  ///
  /// For example, [MainAxisAlignment.start], the default, places the children
  /// at the start (i.e., the left for a [Row] or the top for a [Column]) of the
  /// main axis.
3370
  final MainAxisAlignment mainAxisAlignment;
3371

3372
  /// How much space should be occupied in the main axis.
3373 3374 3375
  ///
  /// After allocating space to children, there might be some remaining free
  /// space. This value controls whether to maximize or minimize the amount of
3376
  /// free space, subject to the incoming layout constraints.
3377 3378 3379 3380 3381
  ///
  /// If some children have a non-zero flex factors (and none have a fit of
  /// [FlexFit.loose]), they will expand to consume all the available space and
  /// there will be no remaining free space to maximize or minimize, making this
  /// value irrelevant to the final layout.
3382 3383
  final MainAxisSize mainAxisSize;

3384
  /// How the children should be placed along the cross axis.
3385 3386 3387
  ///
  /// For example, [CrossAxisAlignment.center], the default, centers the
  /// children in the cross axis (e.g., horizontally for a [Column]).
3388
  final CrossAxisAlignment crossAxisAlignment;
3389

3390 3391 3392 3393 3394
  /// Determines the order to lay children out horizontally and how to interpret
  /// `start` and `end` in the horizontal direction.
  ///
  /// Defaults to the ambient [Directionality].
  ///
3395 3396 3397
  /// If the [direction] is [Axis.horizontal], this controls the order in which
  /// the children are positioned (left-to-right or right-to-left), and the
  /// meaning of the [mainAxisAlignment] property's [MainAxisAlignment.start] and
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435
  /// [MainAxisAlignment.end] values.
  ///
  /// If the [direction] is [Axis.horizontal], and either the
  /// [mainAxisAlignment] is either [MainAxisAlignment.start] or
  /// [MainAxisAlignment.end], or there's more than one child, then the
  /// [textDirection] (or the ambient [Directionality]) must not be null.
  ///
  /// If the [direction] is [Axis.vertical], this controls the meaning of the
  /// [crossAxisAlignment] property's [CrossAxisAlignment.start] and
  /// [CrossAxisAlignment.end] values.
  ///
  /// If the [direction] is [Axis.vertical], and the [crossAxisAlignment] is
  /// either [CrossAxisAlignment.start] or [CrossAxisAlignment.end], then the
  /// [textDirection] (or the ambient [Directionality]) must not be null.
  final TextDirection textDirection;

  /// Determines the order to lay children out vertically and how to interpret
  /// `start` and `end` in the vertical direction.
  ///
  /// Defaults to [VerticalDirection.down].
  ///
  /// If the [direction] is [Axis.vertical], this controls which order children
  /// are painted in (down or up), the meaning of the [mainAxisAlignment]
  /// property's [MainAxisAlignment.start] and [MainAxisAlignment.end] values.
  ///
  /// If the [direction] is [Axis.vertical], and either the [mainAxisAlignment]
  /// is either [MainAxisAlignment.start] or [MainAxisAlignment.end], or there's
  /// more than one child, then the [verticalDirection] must not be null.
  ///
  /// If the [direction] is [Axis.horizontal], this controls the meaning of the
  /// [crossAxisAlignment] property's [CrossAxisAlignment.start] and
  /// [CrossAxisAlignment.end] values.
  ///
  /// If the [direction] is [Axis.horizontal], and the [crossAxisAlignment] is
  /// either [CrossAxisAlignment.start] or [CrossAxisAlignment.end], then the
  /// [verticalDirection] must not be null.
  final VerticalDirection verticalDirection;

3436
  /// If aligning items according to their baseline, which baseline to use.
3437
  final TextBaseline textBaseline;
3438

3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
  bool get _needTextDirection {
    assert(direction != null);
    switch (direction) {
      case Axis.horizontal:
        return true; // because it affects the layout order.
      case Axis.vertical:
        assert(crossAxisAlignment != null);
        return crossAxisAlignment == CrossAxisAlignment.start
            || crossAxisAlignment == CrossAxisAlignment.end;
    }
    return null;
  }

  /// The value to pass to [RenderFlex.textDirection].
  ///
  /// This value is derived from the [textDirection] property and the ambient
  /// [Directionality]. The value is null if there is no need to specify the
  /// text direction. In practice there's always a need to specify the direction
  /// except for vertical flexes (e.g. [Column]s) whose [crossAxisAlignment] is
  /// not dependent on the text direction (not `start` or `end`). In particular,
  /// a [Row] always needs a text direction because the text direction controls
  /// its layout order. (For [Column]s, the layout order is controlled by
  /// [verticalDirection], which is always specified as it does not depend on an
  /// inherited widget and defaults to [VerticalDirection.down].)
  ///
  /// This method exists so that subclasses of [Flex] that create their own
  /// render objects that are derived from [RenderFlex] can do so and still use
  /// the logic for providing a text direction only when it is necessary.
  @protected
  TextDirection getEffectiveTextDirection(BuildContext context) {
    return textDirection ?? (_needTextDirection ? Directionality.of(context) : null);
  }

3472
  @override
3473 3474 3475 3476 3477 3478
  RenderFlex createRenderObject(BuildContext context) {
    return new RenderFlex(
      direction: direction,
      mainAxisAlignment: mainAxisAlignment,
      mainAxisSize: mainAxisSize,
      crossAxisAlignment: crossAxisAlignment,
3479 3480 3481
      textDirection: getEffectiveTextDirection(context),
      verticalDirection: verticalDirection,
      textBaseline: textBaseline,
3482 3483
    );
  }
3484

3485
  @override
3486
  void updateRenderObject(BuildContext context, covariant RenderFlex renderObject) {
3487 3488
    renderObject
      ..direction = direction
3489
      ..mainAxisAlignment = mainAxisAlignment
3490
      ..mainAxisSize = mainAxisSize
3491
      ..crossAxisAlignment = crossAxisAlignment
3492 3493
      ..textDirection = getEffectiveTextDirection(context)
      ..verticalDirection = verticalDirection
3494
      ..textBaseline = textBaseline;
3495
  }
3496 3497

  @override
3498 3499 3500 3501 3502 3503 3504 3505 3506
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<Axis>('direction', direction));
    properties.add(new EnumProperty<MainAxisAlignment>('mainAxisAlignment', mainAxisAlignment));
    properties.add(new EnumProperty<MainAxisSize>('mainAxisSize', mainAxisSize, defaultValue: MainAxisSize.max));
    properties.add(new EnumProperty<CrossAxisAlignment>('crossAxisAlignment', crossAxisAlignment));
    properties.add(new EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
    properties.add(new EnumProperty<VerticalDirection>('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down));
    properties.add(new EnumProperty<TextBaseline>('textBaseline', textBaseline, defaultValue: null));
3507
  }
3508 3509
}

3510
/// A widget that displays its children in a horizontal array.
3511
///
3512 3513
/// To cause a child to expand to fill the available horizontal space, wrap the
/// child in an [Expanded] widget.
3514 3515 3516 3517
///
/// The [Row] widget does not scroll (and in general it is considered an error
/// to have more children in a [Row] than will fit in the available room). If
/// you have a line of widgets and want them to be able to scroll if there is
3518
/// insufficient room, consider using a [ListView].
3519 3520
///
/// For a vertical variant, see [Column].
3521 3522 3523
///
/// If you only have one child, then consider using [Align] or [Center] to
/// position the child.
3524
///
3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549
/// ## Sample code
///
/// This example divides the available space into three (horizontally), and
/// places text centered in the first two cells and the Flutter logo centered in
/// the third:
///
/// ```dart
/// new Row(
///   children: <Widget>[
///     new Expanded(
///       child: new Text('Deliver features faster', textAlign: TextAlign.center),
///     ),
///     new Expanded(
///       child: new Text('Craft beautiful UIs', textAlign: TextAlign.center),
///     ),
///     new Expanded(
///       child: new FittedBox(
///         fit: BoxFit.contain, // otherwise the logo will be tiny
///         child: const FlutterLogo(),
///       ),
///     ),
///   ],
/// )
/// ```
///
3550 3551
/// ## Troubleshooting
///
3552
/// ### Why does my row have a yellow and black warning stripe?
3553
///
3554 3555 3556 3557 3558 3559 3560
/// If the non-flexible contents of the row (those that are not wrapped in
/// [Expanded] or [Flexible] widgets) are together wider than the row itself,
/// then the row is said to have overflowed. When a row overflows, the row does
/// not have any remaining space to share between its [Expanded] and [Flexible]
/// children. The row reports this by drawing a yellow and black striped
/// warning box on the edge that is overflowing. If there is room on the outside
/// of the row, the amount of overflow is printed in red lettering.
3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
///
/// #### Story time
///
/// Suppose, for instance, that you had this code:
///
/// ```dart
/// new Row(
///   children: <Widget>[
///     const FlutterLogo(),
///     const Text('Flutter\'s hot reload helps you quickly and easily experiment, build UIs, add features, and fix bug faster. Experience sub-second reload times, without losing state, on emulators, simulators, and hardware for iOS and Android.'),
///     const Icon(Icons.sentiment_very_satisfied),
///   ],
/// )
/// ```
///
/// The row first asks its first child, the [FlutterLogo], to lay out, at
/// whatever size the logo would like. The logo is friendly and happily decides
/// to be 24 pixels to a side. This leaves lots of room for the next child. The
/// row then asks that next child, the text, to lay out, at whatever size it
/// thinks is best.
///
/// At this point, the text, not knowing how wide is too wide, says "Ok, I will
/// be thiiiiiiiiiiiiiiiiiiiis wide.", and goes well beyond the space that the
/// row has available, not wrapping. The row responds, "That's not fair, now I
/// have no more room available for my other children!", and gets angry and
3586
/// sprouts a yellow and black strip.
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
///
/// The fix is to wrap the second child in an [Expanded] widget, which tells the
/// row that the child should be given the remaining room:
///
/// ```dart
/// new Row(
///   children: <Widget>[
///     const FlutterLogo(),
///     const Expanded(
///       child: const Text('Flutter\'s hot reload helps you quickly and easily experiment, build UIs, add features, and fix bug faster. Experience sub-second reload times, without losing state, on emulators, simulators, and hardware for iOS and Android.'),
///     ),
///     const Icon(Icons.sentiment_very_satisfied),
///   ],
/// )
/// ```
///
/// Now, the row first asks the logo to lay out, and then asks the _icon_ to lay
/// out. The [Icon], like the logo, is happy to take on a reasonable size (also
/// 24 pixels, not coincidentally, since both [FlutterLogo] and [Icon] honor the
/// ambient [IconTheme]). This leaves some room left over, and now the row tells
/// the text exactly how wide to be: the exact width of the remaining space. The
/// text, now happy to comply to a reasonable request, wraps the text within
/// that width, and you end up with a paragraph split over several lines.
///
3611 3612
/// ## Layout algorithm
///
3613
/// _This section describes how a [Row] is rendered by the framework._
3614
/// _See [BoxConstraints] for an introduction to box layout models._
3615
///
3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
/// Layout for a [Row] proceeds in six steps:
///
/// 1. Layout each child a null or zero flex factor (e.g., those that are not
///    [Expanded]) with unbounded horizontal constraints and the incoming
///    vertical constraints. If the [crossAxisAlignment] is
///    [CrossAxisAlignment.stretch], instead use tight vertical constraints that
///    match the incoming max height.
/// 2. Divide the remaining horizontal space among the children with non-zero
///    flex factors (e.g., those that are [Expanded]) according to their flex
///    factor. For example, a child with a flex factor of 2.0 will receive twice
///    the amount of horizontal space as a child with a flex factor of 1.0.
/// 3. Layout each of the remaining children with the same vertical constraints
///    as in step 1, but instead of using unbounded horizontal constraints, use
///    horizontal constraints based on the amount of space allocated in step 2.
///    Children with [Flexible.fit] properties that are [FlexFit.tight] are
///    given tight constraints (i.e., forced to fill the allocated space), and
///    children with [Flexible.fit] properties that are [FlexFit.loose] are
///    given loose constraints (i.e., not forced to fill the allocated space).
/// 4. The height of the [Row] is the maximum height of the children (which will
///    always satisfy the incoming vertical constraints).
/// 5. The width of the [Row] is determined by the [mainAxisSize] property. If
///    the [mainAxisSize] property is [MainAxisSize.max], then the width of the
///    [Row] is the max width of the incoming constraints. If the [mainAxisSize]
///    property is [MainAxisSize.min], then the width of the [Row] is the sum
///    of widths of the children (subject to the incoming constraints).
/// 6. Determine the position for each child according to the
///    [mainAxisAlignment] and the [crossAxisAlignment]. For example, if the
///    [mainAxisAlignment] is [MainAxisAlignment.spaceBetween], any horizontal
///    space that has not been allocated to children is divided evenly and
///    placed between the children.
3646 3647 3648 3649 3650 3651 3652 3653 3654
///
/// See also:
///
///  * [Column], for a vertical equivalent.
///  * [Flex], if you don't know in advance if you want a horizontal or vertical
///    arrangement.
///  * [Expanded], to indicate children that should take all the remaining room.
///  * [Flexible], to indicate children that should share the remaining room but
///    that may by sized smaller (leaving some remaining room unused).
3655
///  * [Spacer], a widget that takes up space proportional to it's flex value.
3656
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
3657
class Row extends Flex {
3658 3659
  /// Creates a horizontal array of children.
  ///
3660 3661 3662 3663 3664 3665 3666 3667 3668
  /// The [direction], [mainAxisAlignment], [mainAxisSize],
  /// [crossAxisAlignment], and [verticalDirection] arguments must not be null.
  /// If [crossAxisAlignment] is [CrossAxisAlignment.baseline], then
  /// [textBaseline] must not be null.
  ///
  /// The [textDirection] argument defaults to the ambient [Directionality], if
  /// any. If there is no ambient directionality, and a text direction is going
  /// to be necessary to determine the layout order (which is always the case
  /// unless the row has no children or only one child) or to disambiguate
3669
  /// `start` or `end` values for the [mainAxisAlignment], the [textDirection]
3670
  /// must not be null.
3671
  Row({
3672
    Key key,
3673 3674 3675
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
    MainAxisSize mainAxisSize = MainAxisSize.max,
    CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
3676
    TextDirection textDirection,
3677
    VerticalDirection verticalDirection = VerticalDirection.down,
3678
    TextBaseline textBaseline,
3679
    List<Widget> children = const <Widget>[],
3680 3681 3682
  }) : super(
    children: children,
    key: key,
3683
    direction: Axis.horizontal,
3684
    mainAxisAlignment: mainAxisAlignment,
3685
    mainAxisSize: mainAxisSize,
3686
    crossAxisAlignment: crossAxisAlignment,
3687 3688 3689
    textDirection: textDirection,
    verticalDirection: verticalDirection,
    textBaseline: textBaseline,
3690
  );
3691 3692
}

3693
/// A widget that displays its children in a vertical array.
3694
///
3695 3696
/// To cause a child to expand to fill the available vertical space, wrap the
/// child in an [Expanded] widget.
3697
///
3698 3699 3700
/// The [Column] widget does not scroll (and in general it is considered an error
/// to have more children in a [Column] than will fit in the available room). If
/// you have a line of widgets and want them to be able to scroll if there is
3701
/// insufficient room, consider using a [ListView].
3702 3703
///
/// For a horizontal variant, see [Row].
3704 3705 3706
///
/// If you only have one child, then consider using [Align] or [Center] to
/// position the child.
3707
///
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
/// ## Sample code
///
/// This example uses a [Column] to arrange three widgets vertically, the last
/// being made to fill all the remaining space.
///
/// ```dart
/// new Column(
///   children: <Widget>[
///     new Text('Deliver features faster'),
///     new Text('Craft beautiful UIs'),
///     new Expanded(
///       child: new FittedBox(
3720
///         fit: BoxFit.contain, // otherwise the logo will be tiny
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749
///         child: const FlutterLogo(),
///       ),
///     ),
///   ],
/// )
/// ```
///
/// In the sample above, the text and the logo are centered on each line. In the
/// following example, the [crossAxisAlignment] is set to
/// [CrossAxisAlignment.start], so that the children are left-aligned. The
/// [mainAxisSize] is set to [MainAxisSize.min], so that the column shrinks to
/// fit the children.
///
/// ```dart
/// new Column(
///   crossAxisAlignment: CrossAxisAlignment.start,
///   mainAxisSize: MainAxisSize.min,
///   children: <Widget>[
///     new Text('We move under cover and we move as one'),
///     new Text('Through the night, we have one shot to live another day'),
///     new Text('We cannot let a stray gunshot give us away'),
///     new Text('We will fight up close, seize the moment and stay in it'),
///     new Text('It’s either that or meet the business end of a bayonet'),
///     new Text('The code word is ‘Rochambeau,’ dig me?'),
///     new Text('Rochambeau!', style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 2.0)),
///   ],
/// )
/// ```
///
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
/// ## Troubleshooting
///
/// ### When the incoming vertical constraints are unbounded
///
/// When a [Column] has one or more [Expanded] or [Flexible] children, and is
/// placed in another [Column], or in a [ListView], or in some other context
/// that does not provide a maximum height constraint for the [Column], you will
/// get an exception at runtime saying that there are children with non-zero
/// flex but the vertical constraints are unbounded.
///
/// The problem, as described in the details that accompany that exception, is
/// that using [Flexible] or [Expanded] means that the remaining space after
/// laying out all the other children must be shared equally, but if the
/// incoming vertical constraints are unbounded, there is infinite remaining
/// space.
///
/// The key to solving this problem is usually to determine why the [Column] is
/// receiving unbounded vertical constraints.
///
/// One common reason for this to happen is that the [Column] has been placed in
/// another [Column] (without using [Expanded] or [Flexible] around the inner
/// nested [Column]). When a [Column] lays out its non-flex children (those that
/// have neither [Expanded] or [Flexible] around them), it gives them unbounded
/// constraints so that they can determine their own dimensions (passing
/// unbounded constraints usually signals to the child that it should
/// shrink-wrap its contents). The solution in this case is typically to just
/// wrap the inner column in an [Expanded] to indicate that it should take the
/// remaining space of the outer column, rather than being allowed to take any
/// amount of room it desires.
///
/// Another reason for this message to be displayed is nesting a [Column] inside
/// a [ListView] or other vertical scrollable. In that scenario, there really is
/// infinite vertical space (the whole point of a vertical scrolling list is to
/// allow infinite space vertically). In such scenarios, it is usually worth
/// examining why the inner [Column] should have an [Expanded] or [Flexible]
/// child: what size should the inner children really be? The solution in this
/// case is typically to remove the [Expanded] or [Flexible] widgets from around
/// the inner children.
///
/// For more discussion about constraints, see [BoxConstraints].
///
/// ### The yellow and black striped banner
///
/// When the contents of a [Column] exceed the amount of space available, the
/// [Column] overflows, and the contents are clipped. In debug mode, a yellow
/// and black striped bar is rendered at the overflowing edge to indicate the
/// problem, and a message is printed below the [Column] saying how much
/// overflow was detected.
///
/// The usual solution is to use a [ListView] rather than a [Column], to enable
/// the contents to scroll when vertical space is limited.
///
3802 3803
/// ## Layout algorithm
///
3804
/// _This section describes how a [Column] is rendered by the framework._
3805
/// _See [BoxConstraints] for an introduction to box layout models._
3806
///
3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838
/// Layout for a [Column] proceeds in six steps:
///
/// 1. Layout each child a null or zero flex factor (e.g., those that are not
///    [Expanded]) with unbounded vertical constraints and the incoming
///    horizontal constraints. If the [crossAxisAlignment] is
///    [CrossAxisAlignment.stretch], instead use tight horizontal constraints
///    that match the incoming max width.
/// 2. Divide the remaining vertical space among the children with non-zero
///    flex factors (e.g., those that are [Expanded]) according to their flex
///    factor. For example, a child with a flex factor of 2.0 will receive twice
///    the amount of vertical space as a child with a flex factor of 1.0.
/// 3. Layout each of the remaining children with the same horizontal
///    constraints as in step 1, but instead of using unbounded vertical
///    constraints, use vertical constraints based on the amount of space
///    allocated in step 2. Children with [Flexible.fit] properties that are
///    [FlexFit.tight] are given tight constraints (i.e., forced to fill the
///    allocated space), and children with [Flexible.fit] properties that are
///    [FlexFit.loose] are given loose constraints (i.e., not forced to fill the
///    allocated space).
/// 4. The width of the [Column] is the maximum width of the children (which
///    will always satisfy the incoming horizontal constraints).
/// 5. The height of the [Column] is determined by the [mainAxisSize] property.
///    If the [mainAxisSize] property is [MainAxisSize.max], then the height of
///    the [Column] is the max height of the incoming constraints. If the
///    [mainAxisSize] property is [MainAxisSize.min], then the height of the
///    [Column] is the sum of heights of the children (subject to the incoming
///    constraints).
/// 6. Determine the position for each child according to the
///    [mainAxisAlignment] and the [crossAxisAlignment]. For example, if the
///    [mainAxisAlignment] is [MainAxisAlignment.spaceBetween], any vertical
///    space that has not been allocated to children is divided evenly and
///    placed between the children.
3839 3840 3841 3842 3843 3844 3845 3846 3847
///
/// See also:
///
///  * [Row], for a horizontal equivalent.
///  * [Flex], if you don't know in advance if you want a horizontal or vertical
///    arrangement.
///  * [Expanded], to indicate children that should take all the remaining room.
///  * [Flexible], to indicate children that should share the remaining room but
///    that may size smaller (leaving some remaining room unused).
3848 3849
///  * [SingleChildScrollView], whose documentation discusses some ways to
///    use a [Column] inside a scrolling container.
3850
///  * [Spacer], a widget that takes up space proportional to it's flex value.
3851
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
3852
class Column extends Flex {
3853 3854
  /// Creates a vertical array of children.
  ///
3855 3856 3857 3858 3859 3860 3861 3862
  /// The [direction], [mainAxisAlignment], [mainAxisSize],
  /// [crossAxisAlignment], and [verticalDirection] arguments must not be null.
  /// If [crossAxisAlignment] is [CrossAxisAlignment.baseline], then
  /// [textBaseline] must not be null.
  ///
  /// The [textDirection] argument defaults to the ambient [Directionality], if
  /// any. If there is no ambient directionality, and a text direction is going
  /// to be necessary to disambiguate `start` or `end` values for the
3863
  /// [crossAxisAlignment], the [textDirection] must not be null.
3864
  Column({
3865
    Key key,
3866 3867 3868
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
    MainAxisSize mainAxisSize = MainAxisSize.max,
    CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
3869
    TextDirection textDirection,
3870
    VerticalDirection verticalDirection = VerticalDirection.down,
3871
    TextBaseline textBaseline,
3872
    List<Widget> children = const <Widget>[],
3873 3874 3875
  }) : super(
    children: children,
    key: key,
3876
    direction: Axis.vertical,
3877
    mainAxisAlignment: mainAxisAlignment,
3878
    mainAxisSize: mainAxisSize,
3879
    crossAxisAlignment: crossAxisAlignment,
3880 3881 3882
    textDirection: textDirection,
    verticalDirection: verticalDirection,
    textBaseline: textBaseline,
3883
  );
3884 3885
}

3886
/// A widget that controls how a child of a [Row], [Column], or [Flex] flexes.
Adam Barth's avatar
Adam Barth committed
3887
///
3888 3889 3890 3891 3892 3893
/// Using a [Flexible] widget gives a child of a [Row], [Column], or [Flex]
/// the flexibility to expand to fill the available space in the main axis
/// (e.g., horizontally for a [Row] or vertically for a [Column]), but, unlike
/// [Expanded], [Flexible] does not require the child to fill the available
/// space.
///
3894 3895 3896 3897
/// A [Flexible] widget must be a descendant of a [Row], [Column], or [Flex],
/// and the path from the [Flexible] widget to its enclosing [Row], [Column], or
/// [Flex] must contain only [StatelessWidget]s or [StatefulWidget]s (not other
/// kinds of widgets, like [RenderObjectWidget]s).
3898 3899 3900 3901
///
/// See also:
///
///  * [Expanded], which forces the child to expand to fill the available space.
3902
///  * [Spacer], a widget that takes up space proportional to it's flex value.
3903
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
3904
class Flexible extends ParentDataWidget<Flex> {
3905 3906
  /// Creates a widget that controls how a child of a [Row], [Column], or [Flex]
  /// flexes.
3907
  const Flexible({
3908
    Key key,
3909 3910
    this.flex = 1,
    this.fit = FlexFit.loose,
3911
    @required Widget child,
3912
  }) : super(key: key, child: child);
3913

Adam Barth's avatar
Adam Barth committed
3914 3915
  /// The flex factor to use for this child
  ///
Adam Barth's avatar
Adam Barth committed
3916 3917 3918 3919
  /// If null or zero, the child is inflexible and determines its own size. If
  /// non-zero, the amount of space the child's can occupy in the main axis is
  /// determined by dividing the free space (after placing the inflexible
  /// children) according to the flex factors of the flexible children.
3920 3921
  final int flex;

Adam Barth's avatar
Adam Barth committed
3922 3923 3924 3925 3926 3927 3928 3929 3930
  /// How a flexible child is inscribed into the available space.
  ///
  /// If [flex] is non-zero, the [fit] determines whether the child fills the
  /// space the parent makes available during layout. If the fit is
  /// [FlexFit.tight], the child is required to fill the available space. If the
  /// fit is [FlexFit.loose], the child can be at most as large as the available
  /// space (but is allowed to be smaller).
  final FlexFit fit;

3931
  @override
3932 3933 3934
  void applyParentData(RenderObject renderObject) {
    assert(renderObject.parentData is FlexParentData);
    final FlexParentData parentData = renderObject.parentData;
Adam Barth's avatar
Adam Barth committed
3935 3936
    bool needsLayout = false;

3937 3938
    if (parentData.flex != flex) {
      parentData.flex = flex;
Adam Barth's avatar
Adam Barth committed
3939 3940 3941 3942 3943 3944 3945 3946 3947
      needsLayout = true;
    }

    if (parentData.fit != fit) {
      parentData.fit = fit;
      needsLayout = true;
    }

    if (needsLayout) {
3948
      final AbstractNode targetParent = renderObject.parent;
3949 3950
      if (targetParent is RenderObject)
        targetParent.markNeedsLayout();
3951 3952
    }
  }
3953

3954
  @override
3955 3956 3957
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new IntProperty('flex', flex));
3958
  }
3959 3960
}

3961 3962
/// A widget that expands a child of a [Row], [Column], or [Flex].
///
3963
/// Using an [Expanded] widget makes a child of a [Row], [Column], or [Flex]
3964 3965
/// expand to fill the available space in the main axis (e.g., horizontally for
/// a [Row] or vertically for a [Column]). If multiple children are expanded,
3966
/// the available space is divided among them according to the [flex] factor.
3967 3968
///
/// An [Expanded] widget must be a descendant of a [Row], [Column], or [Flex],
3969
/// and the path from the [Expanded] widget to its enclosing [Row], [Column], or
3970 3971
/// [Flex] must contain only [StatelessWidget]s or [StatefulWidget]s (not other
/// kinds of widgets, like [RenderObjectWidget]s).
3972 3973 3974 3975
///
/// See also:
///
///  * [Flexible], which does not force the child to fill the available space.
3976
///  * [Spacer], a widget that takes up space proportional to it's flex value.
3977
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
3978 3979 3980
class Expanded extends Flexible {
  /// Creates a widget that expands a child of a [Row], [Column], or [Flex]
  /// expand to fill the available space in the main axis.
3981
  const Expanded({
3982
    Key key,
3983
    int flex = 1,
3984
    @required Widget child,
3985
  }) : super(key: key, flex: flex, fit: FlexFit.tight, child: child);
3986 3987
}

3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
/// A widget that displays its children in multiple horizontal or vertical runs.
///
/// A [Wrap] lays out each child and attempts to place the child adjacent to the
/// previous child in the main axis, given by [direction], leaving [spacing]
/// space in between. If there is not enough space to fit the child, [Wrap]
/// creates a new _run_ adjacent to the existing children in the cross axis.
///
/// After all the children have been allocated to runs, the children within the
/// runs are positioned according to the [alignment] in the main axis and
/// according to the [crossAxisAlignment] in the cross axis.
///
/// The runs themselves are then positioned in the cross axis according to the
/// [runSpacing] and [runAlignment].
Ian Hickson's avatar
Ian Hickson committed
4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035
///
/// ## Sample code
///
/// This example renders some [Chip]s representing four contacts in a [Wrap] so
/// that they flow across lines as necessary.
///
/// ```dart
/// new Wrap(
///   spacing: 8.0, // gap between adjacent chips
///   runSpacing: 4.0, // gap between lines
///   children: <Widget>[
///     new Chip(
///       avatar: new CircleAvatar(backgroundColor: Colors.blue.shade900, child: new Text('AH')),
///       label: new Text('Hamilton'),
///     ),
///     new Chip(
///       avatar: new CircleAvatar(backgroundColor: Colors.blue.shade900, child: new Text('ML')),
///       label: new Text('Lafayette'),
///     ),
///     new Chip(
///       avatar: new CircleAvatar(backgroundColor: Colors.blue.shade900, child: new Text('HM')),
///       label: new Text('Mulligan'),
///     ),
///     new Chip(
///       avatar: new CircleAvatar(backgroundColor: Colors.blue.shade900, child: new Text('JL')),
///       label: new Text('Laurens'),
///     ),
///   ],
/// )
/// ```
///
/// See also:
///
///  * [Row], which places children in one line, and gives control over their
///    alignment and spacing.
4036
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
Adam Barth's avatar
Adam Barth committed
4037
class Wrap extends MultiChildRenderObjectWidget {
4038 4039 4040 4041
  /// Creates a wrap layout.
  ///
  /// By default, the wrap layout is horizontal and both the children and the
  /// runs are aligned to the start.
4042 4043 4044 4045 4046 4047
  ///
  /// The [textDirection] argument defaults to the ambient [Directionality], if
  /// any. If there is no ambient directionality, and a text direction is going
  /// to be necessary to decide which direction to lay the children in or to
  /// disambiguate `start` or `end` values for the main or cross axis
  /// directions, the [textDirection] must not be null.
Adam Barth's avatar
Adam Barth committed
4048 4049
  Wrap({
    Key key,
4050 4051 4052 4053 4054 4055
    this.direction = Axis.horizontal,
    this.alignment = WrapAlignment.start,
    this.spacing = 0.0,
    this.runAlignment = WrapAlignment.start,
    this.runSpacing = 0.0,
    this.crossAxisAlignment = WrapCrossAlignment.start,
4056
    this.textDirection,
4057 4058
    this.verticalDirection = VerticalDirection.down,
    List<Widget> children = const <Widget>[],
Adam Barth's avatar
Adam Barth committed
4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
  }) : super(key: key, children: children);

  /// The direction to use as the main axis.
  ///
  /// For example, if [direction] is [Axis.horizontal], the default, the
  /// children are placed adjacent to one another in a horizontal run until the
  /// available horizontal space is consumed, at which point a subsequent
  /// children are placed in a new run vertically adjacent to the previous run.
  final Axis direction;

  /// How the children within a run should be places in the main axis.
  ///
  /// For example, if [alignment] is [WrapAlignment.center], the children in
4072
  /// each run are grouped together in the center of their run in the main axis.
Adam Barth's avatar
Adam Barth committed
4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099
  ///
  /// Defaults to [WrapAlignment.start].
  ///
  /// See also:
  ///
  ///  * [runAlignment], which controls how the runs are placed relative to each
  ///    other in the cross axis.
  ///  * [crossAxisAlignment], which controls how the children within each run
  ///    are placed relative to each other in the cross axis.
  final WrapAlignment alignment;

  /// How much space to place between children in a run in the main axis.
  ///
  /// For example, if [spacing] is 10.0, the children will be spaced at least
  /// 10.0 logical pixels apart in the main axis.
  ///
  /// If there is additional free space in a run (e.g., because the wrap has a
  /// minimum size that is not filled or because some runs are longer than
  /// others), the additional free space will be allocated according to the
  /// [alignment].
  ///
  /// Defaults to 0.0.
  final double spacing;

  /// How the runs themselves should be placed in the cross axis.
  ///
  /// For example, if [runAlignment] is [WrapAlignment.center], the runs are
4100
  /// grouped together in the center of the overall [Wrap] in the cross axis.
Adam Barth's avatar
Adam Barth committed
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
  ///
  /// Defaults to [WrapAlignment.start].
  ///
  /// See also:
  ///
  ///  * [alignment], which controls how the children within each run are placed
  ///    relative to each other in the main axis.
  ///  * [crossAxisAlignment], which controls how the children within each run
  ///    are placed relative to each other in the cross axis.
  final WrapAlignment runAlignment;

  /// How much space to place between the runs themselves in the cross axis.
  ///
  /// For example, if [runSpacing] is 10.0, the runs will be spaced at least
  /// 10.0 logical pixels apart in the cross axis.
  ///
  /// If there is additional free space in the overall [Wrap] (e.g., because
  /// the wrap has a minimum size that is not filled), the additional free space
  /// will be allocated according to the [runAlignment].
  ///
  /// Defaults to 0.0.
  final double runSpacing;

  /// How the children within a run should be aligned relative to each other in
  /// the cross axis.
  ///
  /// For example, if this is set to [WrapCrossAlignment.end], and the
4128
  /// [direction] is [Axis.horizontal], then the children within each
Adam Barth's avatar
Adam Barth committed
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140
  /// run will have their bottom edges aligned to the bottom edge of the run.
  ///
  /// Defaults to [WrapCrossAlignment.start].
  ///
  /// See also:
  ///
  ///  * [alignment], which controls how the children within each run are placed
  ///    relative to each other in the main axis.
  ///  * [runAlignment], which controls how the runs are placed relative to each
  ///    other in the cross axis.
  final WrapCrossAlignment crossAxisAlignment;

4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
  /// Determines the order to lay children out horizontally and how to interpret
  /// `start` and `end` in the horizontal direction.
  ///
  /// Defaults to the ambient [Directionality].
  ///
  /// If the [direction] is [Axis.horizontal], this controls order in which the
  /// children are positioned (left-to-right or right-to-left), and the meaning
  /// of the [alignment] property's [WrapAlignment.start] and
  /// [WrapAlignment.end] values.
  ///
  /// If the [direction] is [Axis.horizontal], and either the
  /// [alignment] is either [WrapAlignment.start] or [WrapAlignment.end], or
  /// there's more than one child, then the [textDirection] (or the ambient
  /// [Directionality]) must not be null.
  ///
  /// If the [direction] is [Axis.vertical], this controls the order in which
  /// runs are positioned, the meaning of the [runAlignment] property's
  /// [WrapAlignment.start] and [WrapAlignment.end] values, as well as the
  /// [crossAxisAlignment] property's [WrapCrossAlignment.start] and
  /// [WrapCrossAlignment.end] values.
  ///
  /// If the [direction] is [Axis.vertical], and either the
  /// [runAlignment] is either [WrapAlignment.start] or [WrapAlignment.end], the
  /// [crossAxisAlignment] is either [WrapCrossAlignment.start] or
  /// [WrapCrossAlignment.end], or there's more than one child, then the
  /// [textDirection] (or the ambient [Directionality]) must not be null.
  final TextDirection textDirection;

  /// Determines the order to lay children out vertically and how to interpret
  /// `start` and `end` in the vertical direction.
  ///
  /// If the [direction] is [Axis.vertical], this controls which order children
  /// are painted in (down or up), the meaning of the [alignment] property's
  /// [WrapAlignment.start] and [WrapAlignment.end] values.
  ///
  /// If the [direction] is [Axis.vertical], and either the [alignment]
  /// is either [WrapAlignment.start] or [WrapAlignment.end], or there's
  /// more than one child, then the [verticalDirection] must not be null.
  ///
  /// If the [direction] is [Axis.horizontal], this controls the order in which
  /// runs are positioned, the meaning of the [runAlignment] property's
  /// [WrapAlignment.start] and [WrapAlignment.end] values, as well as the
  /// [crossAxisAlignment] property's [WrapCrossAlignment.start] and
  /// [WrapCrossAlignment.end] values.
  ///
  /// If the [direction] is [Axis.horizontal], and either the
  /// [runAlignment] is either [WrapAlignment.start] or [WrapAlignment.end], the
  /// [crossAxisAlignment] is either [WrapCrossAlignment.start] or
  /// [WrapCrossAlignment.end], or there's more than one child, then the
  /// [verticalDirection] must not be null.
  final VerticalDirection verticalDirection;

Adam Barth's avatar
Adam Barth committed
4193 4194 4195 4196 4197 4198 4199 4200 4201
  @override
  RenderWrap createRenderObject(BuildContext context) {
    return new RenderWrap(
      direction: direction,
      alignment: alignment,
      spacing: spacing,
      runAlignment: runAlignment,
      runSpacing: runSpacing,
      crossAxisAlignment: crossAxisAlignment,
4202 4203
      textDirection: textDirection ?? Directionality.of(context),
      verticalDirection: verticalDirection,
Adam Barth's avatar
Adam Barth committed
4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderWrap renderObject) {
    renderObject
      ..direction = direction
      ..alignment = alignment
      ..spacing = spacing
      ..runAlignment = runAlignment
      ..runSpacing = runSpacing
4215 4216 4217 4218 4219 4220
      ..crossAxisAlignment = crossAxisAlignment
      ..textDirection = textDirection ?? Directionality.of(context)
      ..verticalDirection = verticalDirection;
  }

  @override
4221 4222 4223 4224 4225 4226 4227 4228 4229 4230
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<Axis>('direction', direction));
    properties.add(new EnumProperty<WrapAlignment>('alignment', alignment));
    properties.add(new DoubleProperty('spacing', spacing));
    properties.add(new EnumProperty<WrapAlignment>('runAlignment', runAlignment));
    properties.add(new DoubleProperty('runSpacing', runSpacing));
    properties.add(new DoubleProperty('crossAxisAlignment', runSpacing));
    properties.add(new EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
    properties.add(new EnumProperty<VerticalDirection>('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down));
Adam Barth's avatar
Adam Barth committed
4231 4232 4233
  }
}

Ian Hickson's avatar
Ian Hickson committed
4234 4235
/// A widget that sizes and positions children efficiently, according to the
/// logic in a [FlowDelegate].
Adam Barth's avatar
Adam Barth committed
4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
///
/// Flow layouts are optimized for repositioning children using transformation
/// matrices.
///
/// The flow container is sized independently from the children by the
/// [FlowDelegate.getSize] function of the delegate. The children are then sized
/// independently given the constraints from the
/// [FlowDelegate.getConstraintsForChild] function.
///
/// Rather than positioning the children during layout, the children are
/// positioned using transformation matrices during the paint phase using the
/// matrices from the [FlowDelegate.paintChildren] function. The children can be
Ian Hickson's avatar
Ian Hickson committed
4248 4249 4250
/// repositioned efficiently by simply repainting the flow, which happens
/// without the children being laid out again (contrast this with a [Stack],
/// which does the sizing and positioning together during layout).
Adam Barth's avatar
Adam Barth committed
4251
///
Ian Hickson's avatar
Ian Hickson committed
4252 4253 4254 4255
/// The most efficient way to trigger a repaint of the flow is to supply an
/// animation to the constructor of the [FlowDelegate]. The flow will listen to
/// this animation and repaint whenever the animation ticks, avoiding both the
/// build and layout phases of the pipeline.
Adam Barth's avatar
Adam Barth committed
4256 4257 4258
///
/// See also:
///
Ian Hickson's avatar
Ian Hickson committed
4259 4260
///  * [Wrap], which provides the layout model that some other frameworks call
///    "flow", and is otherwise unrelated to [Flow].
4261 4262 4263 4264 4265 4266
///  * [FlowDelegate], which controls the visual presentation of the children.
///  * [Stack], which arranges children relative to the edges of the container.
///  * [CustomSingleChildLayout], which uses a delegate to control the layout of
///    a single child.
///  * [CustomMultiChildLayout], which uses a delegate to position multiple
///    children.
4267
///  * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
Adam Barth's avatar
Adam Barth committed
4268 4269 4270 4271 4272
class Flow extends MultiChildRenderObjectWidget {
  /// Creates a flow layout.
  ///
  /// Wraps each of the given children in a [RepaintBoundary] to avoid
  /// repainting the children when the flow repaints.
4273 4274
  ///
  /// The [delegate] argument must not be null.
Adam Barth's avatar
Adam Barth committed
4275 4276
  Flow({
    Key key,
4277
    @required this.delegate,
4278
    List<Widget> children = const <Widget>[],
4279 4280 4281
  }) : assert(delegate != null),
       super(key: key, children: RepaintBoundary.wrapAll(children));
       // https://github.com/dart-lang/sdk/issues/29277
Adam Barth's avatar
Adam Barth committed
4282 4283 4284 4285 4286 4287

  /// Creates a flow layout.
  ///
  /// Does not wrap the given children in repaint boundaries, unlike the default
  /// constructor. Useful when the child is trivial to paint or already contains
  /// a repaint boundary.
4288 4289
  ///
  /// The [delegate] argument must not be null.
Adam Barth's avatar
Adam Barth committed
4290 4291
  Flow.unwrapped({
    Key key,
4292
    @required this.delegate,
4293
    List<Widget> children = const <Widget>[],
4294 4295
  }) : assert(delegate != null),
       super(key: key, children: children);
Adam Barth's avatar
Adam Barth committed
4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309

  /// The delegate that controls the transformation matrices of the children.
  final FlowDelegate delegate;

  @override
  RenderFlow createRenderObject(BuildContext context) => new RenderFlow(delegate: delegate);

  @override
  void updateRenderObject(BuildContext context, RenderFlow renderObject) {
    renderObject
      ..delegate = delegate;
  }
}

Adam Barth's avatar
Adam Barth committed
4310
/// A paragraph of rich text.
4311
///
4312
/// The [RichText] widget displays text that uses multiple different styles. The
4313
/// text to display is described using a tree of [TextSpan] objects, each of
4314 4315 4316
/// which has an associated style that is used for that subtree. The text might
/// break across multiple lines or might all be displayed on the same line
/// depending on the layout constraints.
4317 4318
///
/// Text displayed in a [RichText] widget must be explicitly styled. When
4319
/// picking which style to use, consider using [DefaultTextStyle.of] the current
4320 4321
/// [BuildContext] to provide defaults. For more details on how to style text in
/// a [RichText] widget, see the documentation for [TextStyle].
4322
///
4323 4324
/// Consider using the [Text] widget to integrate with the [DefaultTextStyle]
/// automatically. When all the text uses the same style, the default constructor
4325 4326
/// is less verbose. The [Text.rich] constructor allows you to style multiple
/// spans with the default text style while still allowing specified styles per
4327
/// span.
4328
///
4329
/// ## Sample code
4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340
///
/// ```dart
/// new RichText(
///   text: new TextSpan(
///     text: 'Hello ',
///     style: DefaultTextStyle.of(context).style,
///     children: <TextSpan>[
///       new TextSpan(text: 'bold', style: new TextStyle(fontWeight: FontWeight.bold)),
///       new TextSpan(text: ' world!'),
///     ],
///   ),
4341
/// )
4342 4343
/// ```
///
4344 4345
/// See also:
///
4346
///  * [TextStyle], which discusses how to style text.
4347 4348 4349
///  * [TextSpan], which is used to describe the text in a paragraph.
///  * [Text], which automatically applies the ambient styles described by a
///    [DefaultTextStyle] to a single string.
Adam Barth's avatar
Adam Barth committed
4350
class RichText extends LeafRenderObjectWidget {
4351 4352
  /// Creates a paragraph of rich text.
  ///
4353
  /// The [text], [textAlign], [softWrap], [overflow], and [textScaleFactor]
Ian Hickson's avatar
Ian Hickson committed
4354
  /// arguments must not be null.
4355 4356 4357
  ///
  /// The [maxLines] property may be null (and indeed defaults to null), but if
  /// it is not null, it must be greater than zero.
Ian Hickson's avatar
Ian Hickson committed
4358 4359 4360
  ///
  /// The [textDirection], if null, defaults to the ambient [Directionality],
  /// which in that case must not be null.
4361
  const RichText({
4362
    Key key,
4363
    @required this.text,
4364
    this.textAlign = TextAlign.start,
Ian Hickson's avatar
Ian Hickson committed
4365
    this.textDirection,
4366 4367 4368
    this.softWrap = true,
    this.overflow = TextOverflow.clip,
    this.textScaleFactor = 1.0,
4369
    this.maxLines,
4370
    this.locale,
4371
  }) : assert(text != null),
Ian Hickson's avatar
Ian Hickson committed
4372
       assert(textAlign != null),
4373 4374 4375
       assert(softWrap != null),
       assert(overflow != null),
       assert(textScaleFactor != null),
4376
       assert(maxLines == null || maxLines > 0),
4377
       super(key: key);
4378

4379
  /// The text to display in this widget.
4380
  final TextSpan text;
4381

4382 4383 4384
  /// How the text should be aligned horizontally.
  final TextAlign textAlign;

Ian Hickson's avatar
Ian Hickson committed
4385 4386 4387 4388 4389 4390 4391 4392 4393
  /// The directionality of the text.
  ///
  /// This decides how [textAlign] values like [TextAlign.start] and
  /// [TextAlign.end] are interpreted.
  ///
  /// This is also used to disambiguate how to render bidirectional text. For
  /// example, if the [text] is an English phrase followed by a Hebrew phrase,
  /// in a [TextDirection.ltr] context the English phrase will be on the left
  /// and the Hebrew phrase to its right, while in a [TextDirection.rtl]
4394
  /// context, the English phrase will be on the right and the Hebrew phrase on
Ian Hickson's avatar
Ian Hickson committed
4395 4396 4397 4398 4399 4400
  /// its left.
  ///
  /// Defaults to the ambient [Directionality], if any. If there is no ambient
  /// [Directionality], then this must not be null.
  final TextDirection textDirection;

4401 4402 4403 4404 4405 4406 4407 4408
  /// Whether the text should break at soft line breaks.
  ///
  /// If false, the glyphs in the text will be positioned as if there was unlimited horizontal space.
  final bool softWrap;

  /// How visual overflow should be handled.
  final TextOverflow overflow;

4409 4410 4411 4412 4413 4414
  /// The number of font pixels for each logical pixel.
  ///
  /// For example, if the text scale factor is 1.5, text will be 50% larger than
  /// the specified font size.
  final double textScaleFactor;

4415 4416 4417
  /// An optional maximum number of lines for the text to span, wrapping if necessary.
  /// If the text exceeds the given number of lines, it will be truncated according
  /// to [overflow].
4418 4419 4420
  ///
  /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the
  /// edge of the box.
4421 4422
  final int maxLines;

4423 4424 4425 4426 4427 4428 4429 4430 4431
  /// Used to select a font when the same Unicode character can
  /// be rendered differently, depending on the locale.
  ///
  /// It's rarely necessary to set this property. By default its value
  /// is inherited from the enclosing app with `Localizations.localeOf(context)`.
  ///
  /// See [RenderParagraph.locale] for more information.
  final Locale locale;

4432
  @override
4433
  RenderParagraph createRenderObject(BuildContext context) {
4434
    assert(textDirection != null || debugCheckHasDirectionality(context));
4435 4436
    return new RenderParagraph(text,
      textAlign: textAlign,
4437
      textDirection: textDirection ?? Directionality.of(context),
4438
      softWrap: softWrap,
4439
      overflow: overflow,
4440 4441
      textScaleFactor: textScaleFactor,
      maxLines: maxLines,
4442
      locale: locale ?? Localizations.localeOf(context, nullOk: true),
4443
    );
4444
  }
4445

4446
  @override
4447
  void updateRenderObject(BuildContext context, RenderParagraph renderObject) {
4448
    assert(textDirection != null || debugCheckHasDirectionality(context));
4449 4450
    renderObject
      ..text = text
4451
      ..textAlign = textAlign
Ian Hickson's avatar
Ian Hickson committed
4452
      ..textDirection = textDirection ?? Directionality.of(context)
4453
      ..softWrap = softWrap
4454
      ..overflow = overflow
4455
      ..textScaleFactor = textScaleFactor
4456
      ..maxLines = maxLines
4457
      ..locale = locale ?? Localizations.localeOf(context, nullOk: true);
4458
  }
4459 4460

  @override
4461 4462 4463 4464 4465 4466 4467 4468 4469
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<TextAlign>('textAlign', textAlign, defaultValue: TextAlign.start));
    properties.add(new EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
    properties.add(new FlagProperty('softWrap', value: softWrap, ifTrue: 'wrapping at box width', ifFalse: 'no wrapping except at line break characters', showName: true));
    properties.add(new EnumProperty<TextOverflow>('overflow', overflow, defaultValue: TextOverflow.clip));
    properties.add(new DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: 1.0));
    properties.add(new IntProperty('maxLines', maxLines, ifNull: 'unlimited'));
    properties.add(new StringProperty('text', text.toPlainText()));
4470
  }
4471 4472
}

4473
/// A widget that displays a [dart:ui.Image] directly.
4474
///
4475 4476
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
4477
///
4478
/// This widget is rarely used directly. Instead, consider using [Image].
4479
class RawImage extends LeafRenderObjectWidget {
4480 4481
  /// Creates a widget that displays an image.
  ///
Ian Hickson's avatar
Ian Hickson committed
4482 4483
  /// The [scale], [alignment], [repeat], and [matchTextDirection] arguments must
  /// not be null.
4484
  const RawImage({
4485 4486 4487 4488
    Key key,
    this.image,
    this.width,
    this.height,
4489
    this.scale = 1.0,
Adam Barth's avatar
Adam Barth committed
4490
    this.color,
4491
    this.colorBlendMode,
4492
    this.fit,
4493 4494
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
Ian Hickson's avatar
Ian Hickson committed
4495
    this.centerSlice,
4496
    this.matchTextDirection = false,
4497
  }) : assert(scale != null),
Ian Hickson's avatar
Ian Hickson committed
4498
       assert(alignment != null),
4499
       assert(repeat != null),
Ian Hickson's avatar
Ian Hickson committed
4500
       assert(matchTextDirection != null),
4501
       super(key: key);
4502

4503
  /// The image to display.
4504
  final ui.Image image;
4505 4506 4507 4508 4509

  /// If non-null, require the image to have this width.
  ///
  /// If null, the image will pick a size that best preserves its intrinsic
  /// aspect ratio.
4510
  final double width;
4511 4512 4513 4514 4515

  /// If non-null, require the image to have this height.
  ///
  /// If null, the image will pick a size that best preserves its intrinsic
  /// aspect ratio.
4516
  final double height;
4517

4518
  /// Specifies the image's scale.
4519 4520 4521 4522
  ///
  /// Used when determining the best display size for the image.
  final double scale;

4523
  /// If non-null, this color is blended with each image pixel using [colorBlendMode].
Adam Barth's avatar
Adam Barth committed
4524
  final Color color;
4525

4526 4527 4528 4529 4530 4531 4532 4533 4534 4535
  /// Used to combine [color] with this image.
  ///
  /// The default is [BlendMode.srcIn]. In terms of the blend mode, [color] is
  /// the source and this image is the destination.
  ///
  /// See also:
  ///
  ///  * [BlendMode], which includes an illustration of the effect of each blend mode.
  final BlendMode colorBlendMode;

Adam Barth's avatar
Adam Barth committed
4536
  /// How to inscribe the image into the space allocated during layout.
4537 4538 4539
  ///
  /// The default varies based on the other fields. See the discussion at
  /// [paintImage].
4540
  final BoxFit fit;
4541 4542 4543

  /// How to align the image within its bounds.
  ///
Ian Hickson's avatar
Ian Hickson committed
4544
  /// The alignment aligns the given position in the image to the given position
4545
  /// in the layout bounds. For example, an [Alignment] alignment of (-1.0,
4546 4547
  /// -1.0) aligns the image to the top-left corner of its layout bounds, while a
  /// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
Ian Hickson's avatar
Ian Hickson committed
4548
  /// image with the bottom right corner of its layout bounds. Similarly, an
4549
  /// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
Ian Hickson's avatar
Ian Hickson committed
4550 4551 4552 4553 4554 4555
  /// middle of the bottom edge of its layout bounds.
  ///
  /// To display a subpart of an image, consider using a [CustomPainter] and
  /// [Canvas.drawImageRect].
  ///
  /// If the [alignment] is [TextDirection]-dependent (i.e. if it is a
4556
  /// [AlignmentDirectional]), then an ambient [Directionality] widget
Ian Hickson's avatar
Ian Hickson committed
4557 4558
  /// must be in scope.
  ///
4559
  /// Defaults to [Alignment.center].
4560 4561 4562 4563 4564 4565 4566
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
4567
  final AlignmentGeometry alignment;
4568 4569

  /// How to paint any portions of the layout bounds not covered by the image.
4570
  final ImageRepeat repeat;
4571 4572 4573 4574 4575 4576 4577 4578

  /// The center slice for a nine-patch image.
  ///
  /// The region of the image inside the center slice will be stretched both
  /// horizontally and vertically to fit the image into its destination. The
  /// region of the image above and below the center slice will be stretched
  /// only horizontally and the region of the image to the left and right of
  /// the center slice will be stretched only vertically.
4579
  final Rect centerSlice;
4580

Ian Hickson's avatar
Ian Hickson committed
4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
  /// Whether to paint the image in the direction of the [TextDirection].
  ///
  /// If this is true, then in [TextDirection.ltr] contexts, the image will be
  /// drawn with its origin in the top left (the "normal" painting direction for
  /// images); and in [TextDirection.rtl] contexts, the image will be drawn with
  /// a scaling factor of -1 in the horizontal direction so that the origin is
  /// in the top right.
  ///
  /// This is occasionally used with images in right-to-left environments, for
  /// images that were designed for left-to-right locales. Be careful, when
  /// using this, to not flip images with integral shadows, text, or other
  /// effects that will look incorrect when flipped.
  ///
  /// If this is true, there must be an ambient [Directionality] widget in
  /// scope.
  final bool matchTextDirection;

4598
  @override
4599
  RenderImage createRenderObject(BuildContext context) {
4600
    assert((!matchTextDirection && alignment is Alignment) || debugCheckHasDirectionality(context));
4601 4602 4603 4604 4605 4606 4607 4608 4609 4610
    return new RenderImage(
      image: image,
      width: width,
      height: height,
      scale: scale,
      color: color,
      colorBlendMode: colorBlendMode,
      fit: fit,
      alignment: alignment,
      repeat: repeat,
Ian Hickson's avatar
Ian Hickson committed
4611 4612
      centerSlice: centerSlice,
      matchTextDirection: matchTextDirection,
4613
      textDirection: matchTextDirection || alignment is! Alignment ? Directionality.of(context) : null,
4614 4615
    );
  }
4616

4617
  @override
4618
  void updateRenderObject(BuildContext context, RenderImage renderObject) {
4619 4620 4621 4622 4623 4624
    renderObject
      ..image = image
      ..width = width
      ..height = height
      ..scale = scale
      ..color = color
4625
      ..colorBlendMode = colorBlendMode
4626 4627 4628
      ..alignment = alignment
      ..fit = fit
      ..repeat = repeat
Ian Hickson's avatar
Ian Hickson committed
4629 4630
      ..centerSlice = centerSlice
      ..matchTextDirection = matchTextDirection
4631
      ..textDirection = matchTextDirection || alignment is! Alignment ? Directionality.of(context) : null;
4632
  }
4633

4634
  @override
4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<ui.Image>('image', image));
    properties.add(new DoubleProperty('width', width, defaultValue: null));
    properties.add(new DoubleProperty('height', height, defaultValue: null));
    properties.add(new DoubleProperty('scale', scale, defaultValue: 1.0));
    properties.add(new DiagnosticsProperty<Color>('color', color, defaultValue: null));
    properties.add(new EnumProperty<BlendMode>('colorBlendMode', colorBlendMode, defaultValue: null));
    properties.add(new EnumProperty<BoxFit>('fit', fit, defaultValue: null));
    properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null));
    properties.add(new EnumProperty<ImageRepeat>('repeat', repeat, defaultValue: ImageRepeat.noRepeat));
    properties.add(new DiagnosticsProperty<Rect>('centerSlice', centerSlice, defaultValue: null));
    properties.add(new FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'));
4648
  }
4649 4650
}

4651
/// A widget that determines the default asset bundle for its descendants.
4652
///
4653 4654
/// For example, used by [Image] to determine which bundle to use for
/// [AssetImage]s if no bundle is specified explicitly.
4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695
///
/// ## Sample code
///
/// This can be used in tests to override what the current asset bundle is, thus
/// allowing specific resources to be injected into the widget under test.
///
/// For example, a test could create a test asset bundle like this:
///
/// ```dart
/// class TestAssetBundle extends CachingAssetBundle {
///   @override
///   Future<ByteData> load(String key) async {
///     if (key == 'resources/test')
///       return new ByteData.view(new Uint8List.fromList(utf8.encode('Hello World!')).buffer);
///     return null;
///   }
/// }
/// ```
///
/// ...then wrap the widget under test with a [DefaultAssetBundle] using this
/// bundle implementation:
///
/// ```dart
/// await tester.pumpWidget(
///   new MaterialApp(
///     home: new DefaultAssetBundle(
///       bundle: new TestAssetBundle(),
///       child: new TestWidget(),
///     ),
///   ),
/// );
/// ```
///
/// Assuming that `TestWidget` uses [DefaultAssetBundle.of] to obtain its
/// [AssetBundle], it will now see the [TestAssetBundle]'s "Hello World!" data
/// when requesting the "resources/test" asset.
///
/// See also:
///
///  * [AssetBundle], the interface for asset bundles.
///  * [rootBundle], the default default asset bundle.
Adam Barth's avatar
Adam Barth committed
4696
class DefaultAssetBundle extends InheritedWidget {
4697 4698 4699
  /// Creates a widget that determines the default asset bundle for its descendants.
  ///
  /// The [bundle] and [child] arguments must not be null.
4700
  const DefaultAssetBundle({
Adam Barth's avatar
Adam Barth committed
4701
    Key key,
4702 4703
    @required this.bundle,
    @required Widget child
4704 4705 4706
  }) : assert(bundle != null),
       assert(child != null),
       super(key: key, child: child);
Adam Barth's avatar
Adam Barth committed
4707

4708
  /// The bundle to use as a default.
Adam Barth's avatar
Adam Barth committed
4709 4710
  final AssetBundle bundle;

4711 4712 4713 4714 4715
  /// The bundle from the closest instance of this class that encloses
  /// the given context.
  ///
  /// If there is no [DefaultAssetBundle] ancestor widget in the tree
  /// at the given context, then this will return the [rootBundle].
4716 4717 4718 4719 4720 4721
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// AssetBundle bundle = DefaultAssetBundle.of(context);
  /// ```
Adam Barth's avatar
Adam Barth committed
4722
  static AssetBundle of(BuildContext context) {
4723
    final DefaultAssetBundle result = context.inheritFromWidgetOfExactType(DefaultAssetBundle);
4724
    return result?.bundle ?? rootBundle;
Adam Barth's avatar
Adam Barth committed
4725 4726
  }

4727
  @override
4728
  bool updateShouldNotify(DefaultAssetBundle oldWidget) => bundle != oldWidget.bundle;
Adam Barth's avatar
Adam Barth committed
4729 4730
}

4731 4732 4733 4734 4735
/// An adapter for placing a specific [RenderBox] in the widget tree.
///
/// A given render object can be placed at most once in the widget tree. This
/// widget enforces that restriction by keying itself using a [GlobalObjectKey]
/// for the given render object.
Hixie's avatar
Hixie committed
4736
class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget {
4737 4738 4739 4740
  /// Creates an adapter for placing a specific [RenderBox] in the widget tree.
  ///
  /// The [renderBox] argument must not be null.
  WidgetToRenderBoxAdapter({
4741
    @required this.renderBox,
4742 4743
    this.onBuild,
  }) : assert(renderBox != null),
4744 4745 4746 4747
       // WidgetToRenderBoxAdapter objects are keyed to their render box. This
       // prevents the widget being used in the widget hierarchy in two different
       // places, which would cause the RenderBox to get inserted in multiple
       // places in the RenderObject tree.
4748
       super(key: new GlobalObjectKey(renderBox));
Hixie's avatar
Hixie committed
4749

4750
  /// The render box to place in the widget tree.
Hixie's avatar
Hixie committed
4751 4752
  final RenderBox renderBox;

4753 4754 4755 4756 4757 4758
  /// Called when it is safe to update the render box and its descendants. If
  /// you update the RenderObject subtree under this widget outside of
  /// invocations of this callback, features like hit-testing will fail as the
  /// tree will be dirty.
  final VoidCallback onBuild;

4759
  @override
4760
  RenderBox createRenderObject(BuildContext context) => renderBox;
4761

4762
  @override
4763
  void updateRenderObject(BuildContext context, RenderBox renderObject) {
4764 4765 4766
    if (onBuild != null)
      onBuild();
  }
Hixie's avatar
Hixie committed
4767 4768
}

4769

4770
// EVENT HANDLING
4771

4772
/// A widget that calls callbacks in response to pointer events.
4773 4774 4775
///
/// Rather than listening for raw pointer events, consider listening for
/// higher-level gestures using [GestureDetector].
4776
///
4777 4778 4779 4780
/// ## Layout behavior
///
/// _See [BoxConstraints] for an introduction to box layout models._
///
4781 4782
/// If it has a child, this widget defers to the child for sizing behavior. If
/// it does not have a child, it grows to fit the parent instead.
4783
class Listener extends SingleChildRenderObjectWidget {
4784 4785 4786
  /// Creates a widget that forwards point events to callbacks.
  ///
  /// The [behavior] argument defaults to [HitTestBehavior.deferToChild].
4787
  const Listener({
4788 4789 4790 4791
    Key key,
    this.onPointerDown,
    this.onPointerMove,
    this.onPointerUp,
4792
    this.onPointerCancel,
4793
    this.behavior = HitTestBehavior.deferToChild,
4794
    Widget child
4795 4796
  }) : assert(behavior != null),
       super(key: key, child: child);
4797

4798
  /// Called when a pointer comes into contact with the screen at this object.
Ian Hickson's avatar
Ian Hickson committed
4799
  final PointerDownEventListener onPointerDown;
4800 4801

  /// Called when a pointer that triggered an [onPointerDown] changes position.
Ian Hickson's avatar
Ian Hickson committed
4802
  final PointerMoveEventListener onPointerMove;
4803 4804

  /// Called when a pointer that triggered an [onPointerDown] is no longer in contact with the screen.
Ian Hickson's avatar
Ian Hickson committed
4805
  final PointerUpEventListener onPointerUp;
4806 4807

  /// Called when the input from a pointer that triggered an [onPointerDown] is no longer directed towards this receiver.
Ian Hickson's avatar
Ian Hickson committed
4808
  final PointerCancelEventListener onPointerCancel;
4809 4810

  /// How to behave during hit testing.
4811
  final HitTestBehavior behavior;
4812

4813
  @override
4814 4815 4816 4817 4818 4819 4820 4821 4822
  RenderPointerListener createRenderObject(BuildContext context) {
    return new RenderPointerListener(
      onPointerDown: onPointerDown,
      onPointerMove: onPointerMove,
      onPointerUp: onPointerUp,
      onPointerCancel: onPointerCancel,
      behavior: behavior
    );
  }
4823

4824
  @override
4825
  void updateRenderObject(BuildContext context, RenderPointerListener renderObject) {
4826 4827 4828 4829 4830 4831
    renderObject
      ..onPointerDown = onPointerDown
      ..onPointerMove = onPointerMove
      ..onPointerUp = onPointerUp
      ..onPointerCancel = onPointerCancel
      ..behavior = behavior;
4832
  }
4833

4834
  @override
4835 4836
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
4837
    final List<String> listeners = <String>[];
4838 4839 4840 4841 4842 4843 4844 4845
    if (onPointerDown != null)
      listeners.add('down');
    if (onPointerMove != null)
      listeners.add('move');
    if (onPointerUp != null)
      listeners.add('up');
    if (onPointerCancel != null)
      listeners.add('cancel');
4846 4847
    properties.add(new IterableProperty<String>('listeners', listeners, ifEmpty: '<none>'));
    properties.add(new EnumProperty<HitTestBehavior>('behavior', behavior));
4848
  }
4849
}
4850

4851
/// A widget that creates a separate display list for its child.
4852 4853 4854
///
/// This widget creates a separate display list for its child, which
/// can improve performance if the subtree repaints at different times than
4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901
/// the surrounding parts of the tree.
///
/// This is useful since [RenderObject.paint] may be triggered even if its
/// associated [Widget] instances did not change or rebuild. A [RenderObject]
/// will repaint whenever any [RenderObject] that shares the same [Layer] is
/// marked as being dirty and needing paint (see [RenderObject.markNeedsPaint]),
/// such as when an ancestor scrolls or when an ancestor or descendant animates.
///
/// Containing [RenderObject.paint] to parts of the render subtree that are
/// actually visually changing using [RepaintBoundary] explicitly or implicitly
/// is therefore critical to minimizing redundant work and improving the app's
/// performance.
///
/// When a [RenderObject] is flagged as needing to paint via
/// [RenderObject.markNeedsPaint], the nearest ancestor [RenderObject] with
/// [RenderObject.isRepaintBoundary], up to possibly the root of the application,
/// is requested to repaint. That nearest ancestor's [RenderObject.paint] method
/// will cause _all_ of its descendant [RenderObject]s to repaint in the same
/// layer.
///
/// [RepaintBoundary] is therefore used, both while propagating the
/// `markNeedsPaint` flag up the render tree and while traversing down the
/// render tree via [RenderObject.paintChild], to strategically contain repaints
/// to the render subtree that visually changed for performance. This is done
/// because the [RepaintBoundary] widget creates a [RenderObject] that always
/// has a [Layer], decoupling ancestor render objects from the descendant
/// render objects.
///
/// [RepaintBoundary] has the further side-effect of possibly hinting to the
/// engine that it should further optimize animation performance if the render
/// subtree behind the [RepaintBoundary] is sufficiently complex and is static
/// while the surrounding tree changes frequently. In those cases, the engine
/// may choose to pay a one time cost of rasterizing and caching the pixel
/// values of the subtree for faster future GPU re-rendering speed.
///
/// Several framework widgets insert [RepaintBoundary] widgets to mark natural
/// separation points in applications. For instance, contents in Material Design
/// drawers typically don't change while the drawer opens and closes, so
/// repaints are automatically contained to regions inside or outside the drawer
/// when using the [Drawer] widget during transitions.
///
/// See also:
///
///  * [debugRepaintRainbowEnabled], a debugging flag to help visually monitor
///    render tree repaints in a running app.
///  * [debugProfilePaintsEnabled], a debugging flag to show render tree
///    repaints in the observatory's timeline view.
4902
class RepaintBoundary extends SingleChildRenderObjectWidget {
4903
  /// Creates a widget that isolates repaints.
4904
  const RepaintBoundary({ Key key, Widget child }) : super(key: key, child: child);
4905

4906 4907 4908 4909
  /// Wraps the given child in a [RepaintBoundary].
  ///
  /// The key for the [RepaintBoundary] is derived either from the child's key
  /// (if the child has a non-null key) or from the given `childIndex`.
4910
  factory RepaintBoundary.wrap(Widget child, int childIndex) {
4911
    assert(child != null);
4912
    final Key key = child.key != null ? new ValueKey<Key>(child.key) : new ValueKey<int>(childIndex);
4913 4914 4915
    return new RepaintBoundary(key: key, child: child);
  }

4916 4917 4918 4919 4920
  /// Wraps each of the given children in [RepaintBoundary]s.
  ///
  /// The key for each [RepaintBoundary] is derived either from the wrapped
  /// child's key (if the wrapped child has a non-null key) or from the wrapped
  /// child's index in the list.
Adam Barth's avatar
Adam Barth committed
4921
  static List<RepaintBoundary> wrapAll(List<Widget> widgets) {
4922
    final List<RepaintBoundary> result = new List<RepaintBoundary>(widgets.length);
Adam Barth's avatar
Adam Barth committed
4923 4924 4925 4926 4927
    for (int i = 0; i < result.length; ++i)
      result[i] = new RepaintBoundary.wrap(widgets[i], i);
    return result;
  }

4928
  @override
4929
  RenderRepaintBoundary createRenderObject(BuildContext context) => new RenderRepaintBoundary();
4930 4931
}

4932
/// A widget that is invisible during hit testing.
4933
///
4934
/// When [ignoring] is true, this widget (and its subtree) is invisible
4935
/// to hit testing. It still consumes space during layout and paints its child
4936
/// as usual. It just cannot be the target of located events, because it returns
4937
/// false from [RenderBox.hitTest].
4938
///
4939
/// When [ignoringSemantics] is true, the subtree will be invisible to
4940 4941
/// the semantics layer (and thus e.g. accessibility tools). If
/// [ignoringSemantics] is null, it uses the value of [ignoring].
4942 4943 4944 4945 4946
///
/// See also:
///
///  * [AbsorbPointer], which also prevents its children from receiving pointer
///    events but is itself visible to hit testing.
4947
class IgnorePointer extends SingleChildRenderObjectWidget {
4948
  /// Creates a widget that is invisible to hit testing.
4949 4950 4951
  ///
  /// The [ignoring] argument must not be null. If [ignoringSemantics], this
  /// render object will be ignored for semantics if [ignoring] is true.
4952
  const IgnorePointer({
4953
    Key key,
4954
    this.ignoring = true,
4955 4956
    this.ignoringSemantics,
    Widget child
4957 4958
  }) : assert(ignoring != null),
       super(key: key, child: child);
4959

4960 4961 4962 4963
  /// Whether this widget is ignored during hit testing.
  ///
  /// Regardless of whether this widget is ignored during hit testing, it will
  /// still consume space during layout and be visible during painting.
4964
  final bool ignoring;
4965 4966 4967 4968 4969 4970 4971

  /// Whether the semantics of this widget is ignored when compiling the semantics tree.
  ///
  /// If null, defaults to value of [ignoring].
  ///
  /// See [SemanticsNode] for additional information about the semantics tree.
  final bool ignoringSemantics;
4972

4973
  @override
4974 4975 4976 4977 4978 4979
  RenderIgnorePointer createRenderObject(BuildContext context) {
    return new RenderIgnorePointer(
      ignoring: ignoring,
      ignoringSemantics: ignoringSemantics
    );
  }
4980

4981
  @override
4982
  void updateRenderObject(BuildContext context, RenderIgnorePointer renderObject) {
4983 4984 4985
    renderObject
      ..ignoring = ignoring
      ..ignoringSemantics = ignoringSemantics;
4986
  }
4987 4988

  @override
4989 4990 4991 4992
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<bool>('ignoring', ignoring));
    properties.add(new DiagnosticsProperty<bool>('ignoringSemantics', ignoringSemantics, defaultValue: null));
4993
  }
4994
}
4995

4996 4997
/// A widget that absorbs pointers during hit testing.
///
4998
/// When [absorbing] is true, this widget prevents its subtree from receiving
4999 5000
/// pointer events by terminating hit testing at itself. It still consumes space
/// during layout and paints its child as usual. It just prevents its children
5001
/// from being the target of located events, because it returns true from
5002
/// [RenderBox.hitTest].
5003 5004 5005 5006 5007
///
/// See also:
///
///  * [IgnorePointer], which also prevents its children from receiving pointer
///    events but is itself invisible to hit testing.
5008 5009 5010 5011
class AbsorbPointer extends SingleChildRenderObjectWidget {
  /// Creates a widget that absorbs pointers during hit testing.
  ///
  /// The [absorbing] argument must not be null
5012
  const AbsorbPointer({
5013
    Key key,
5014
    this.absorbing = true,
5015 5016
    Widget child,
    this.ignoringSemantics,
5017 5018
  }) : assert(absorbing != null),
       super(key: key, child: child);
5019 5020 5021 5022 5023 5024 5025 5026

  /// Whether this widget absorbs pointers during hit testing.
  ///
  /// Regardless of whether this render object absorbs pointers during hit
  /// testing, it will still consume space during layout and be visible during
  /// painting.
  final bool absorbing;

5027 5028 5029 5030 5031 5032 5033 5034
  /// Whether the semantics of this render object is ignored when compiling the
  /// semantics tree.
  ///
  /// If null, defaults to the value of [absorbing].
  ///
  /// See [SemanticsNode] for additional information about the semantics tree.
  final bool ignoringSemantics;

5035
  @override
5036 5037 5038 5039 5040 5041
  RenderAbsorbPointer createRenderObject(BuildContext context) {
    return new RenderAbsorbPointer(
      absorbing: absorbing,
      ignoringSemantics: ignoringSemantics,
    );
  }
5042 5043 5044

  @override
  void updateRenderObject(BuildContext context, RenderAbsorbPointer renderObject) {
5045 5046 5047 5048 5049 5050 5051 5052 5053 5054
    renderObject
      ..absorbing = absorbing
      ..ignoringSemantics = ignoringSemantics;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<bool>('absorbing', absorbing));
    properties.add(new DiagnosticsProperty<bool>('ignoringSemantics', ignoringSemantics, defaultValue: null));
5055 5056 5057
  }
}

5058
/// Holds opaque meta data in the render tree.
5059 5060 5061 5062 5063
///
/// Useful for decorating the render tree with information that will be consumed
/// later. For example, you could store information in the render tree that will
/// be used when the user interacts with the render tree but has no visual
/// impact prior to the interaction.
5064
class MetaData extends SingleChildRenderObjectWidget {
5065
  /// Creates a widget that hold opaque meta data.
5066 5067
  ///
  /// The [behavior] argument defaults to [HitTestBehavior.deferToChild].
5068
  const MetaData({
5069 5070
    Key key,
    this.metaData,
5071
    this.behavior = HitTestBehavior.deferToChild,
5072
    Widget child
5073 5074 5075 5076 5077 5078 5079 5080 5081
  }) : super(key: key, child: child);

  /// Opaque meta data ignored by the render tree
  final dynamic metaData;

  /// How to behave during hit testing.
  final HitTestBehavior behavior;

  @override
5082 5083 5084 5085 5086 5087
  RenderMetaData createRenderObject(BuildContext context) {
    return new RenderMetaData(
      metaData: metaData,
      behavior: behavior
    );
  }
5088 5089 5090 5091 5092 5093 5094 5095 5096

  @override
  void updateRenderObject(BuildContext context, RenderMetaData renderObject) {
    renderObject
      ..metaData = metaData
      ..behavior = behavior;
  }

  @override
5097 5098 5099 5100
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new EnumProperty<HitTestBehavior>('behavior', behavior));
    properties.add(new DiagnosticsProperty<dynamic>('metaData', metaData));
5101 5102 5103
  }
}

5104 5105 5106

// UTILITY NODES

5107 5108
/// A widget that annotates the widget tree with a description of the meaning of
/// the widgets.
5109 5110 5111
///
/// Used by accessibility tools, search engines, and other semantic analysis
/// software to determine the meaning of the application.
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126
///
/// See also:
///
/// * [MergeSemantics], which marks a subtree as being a single node for
///   accessibility purposes.
/// * [ExcludeSemantics], which excludes a subtree from the semantics tree
///   (which might be useful if it is, e.g., totally decorative and not
///   important to the user).
/// * [RenderObject.semanticsAnnotator], the rendering library API through which
///   the [Semantics] widget is actually implemented.
/// * [SemanticsNode], the object used by the rendering library to represent
///   semantics in the semantics tree.
/// * [SemanticsDebugger], an overlay to help visualize the semantics tree. Can
///   be enabled using [WidgetsApp.showSemanticsDebugger] or
///   [MaterialApp.showSemanticsDebugger].
5127
@immutable
5128
class Semantics extends SingleChildRenderObjectWidget {
5129 5130
  /// Creates a semantic annotation.
  ///
5131
  /// The [container] argument must not be null. To create a `const` instance
5132 5133 5134 5135
  /// of [Semantics], use the [Semantics.fromProperties] constructor.
  ///
  /// See also:
  ///
5136
  ///  * [SemanticsSortKey] for a class that determines accessibility traversal
5137
  ///    order.
5138 5139 5140
  Semantics({
    Key key,
    Widget child,
5141 5142
    bool container = false,
    bool explicitChildNodes = false,
5143
    bool excludeSemantics = false,
5144
    bool enabled,
5145 5146
    bool checked,
    bool selected,
5147
    bool toggled,
5148
    bool button,
5149 5150 5151 5152
    bool header,
    bool textField,
    bool focused,
    bool inMutuallyExclusiveGroup,
5153
    bool obscured,
5154 5155
    bool scopesRoute,
    bool namesRoute,
5156
    bool hidden,
5157 5158
    bool image,
    bool liveRegion,
5159 5160 5161 5162 5163
    String label,
    String value,
    String increasedValue,
    String decreasedValue,
    String hint,
5164 5165
    String onTapHint,
    String onLongPressHint,
5166
    TextDirection textDirection,
5167
    SemanticsSortKey sortKey,
5168 5169 5170 5171 5172 5173 5174 5175
    VoidCallback onTap,
    VoidCallback onLongPress,
    VoidCallback onScrollLeft,
    VoidCallback onScrollRight,
    VoidCallback onScrollUp,
    VoidCallback onScrollDown,
    VoidCallback onIncrease,
    VoidCallback onDecrease,
5176 5177 5178
    VoidCallback onCopy,
    VoidCallback onCut,
    VoidCallback onPaste,
5179
    VoidCallback onDismiss,
5180 5181
    MoveCursorHandler onMoveCursorForwardByCharacter,
    MoveCursorHandler onMoveCursorBackwardByCharacter,
5182
    SetSelectionHandler onSetSelection,
5183 5184
    VoidCallback onDidGainAccessibilityFocus,
    VoidCallback onDidLoseAccessibilityFocus,
5185
    Map<CustomSemanticsAction, VoidCallback> customSemanticsActions,
5186 5187 5188 5189 5190
  }) : this.fromProperties(
    key: key,
    child: child,
    container: container,
    explicitChildNodes: explicitChildNodes,
5191
    excludeSemantics: excludeSemantics,
5192
    properties: new SemanticsProperties(
5193
      enabled: enabled,
5194
      checked: checked,
5195
      toggled: toggled,
5196 5197
      selected: selected,
      button: button,
5198 5199 5200 5201
      header: header,
      textField: textField,
      focused: focused,
      inMutuallyExclusiveGroup: inMutuallyExclusiveGroup,
5202
      obscured: obscured,
5203 5204
      scopesRoute: scopesRoute,
      namesRoute: namesRoute,
5205
      hidden: hidden,
5206 5207
      image: image,
      liveRegion: liveRegion,
5208 5209 5210 5211 5212 5213
      label: label,
      value: value,
      increasedValue: increasedValue,
      decreasedValue: decreasedValue,
      hint: hint,
      textDirection: textDirection,
5214
      sortKey: sortKey,
5215 5216 5217 5218 5219 5220 5221 5222
      onTap: onTap,
      onLongPress: onLongPress,
      onScrollLeft: onScrollLeft,
      onScrollRight: onScrollRight,
      onScrollUp: onScrollUp,
      onScrollDown: onScrollDown,
      onIncrease: onIncrease,
      onDecrease: onDecrease,
5223 5224 5225
      onCopy: onCopy,
      onCut: onCut,
      onPaste: onPaste,
5226 5227
      onMoveCursorForwardByCharacter: onMoveCursorForwardByCharacter,
      onMoveCursorBackwardByCharacter: onMoveCursorBackwardByCharacter,
5228 5229
      onDidGainAccessibilityFocus: onDidGainAccessibilityFocus,
      onDidLoseAccessibilityFocus: onDidLoseAccessibilityFocus,
5230 5231
      onDismiss: onDismiss,
      onSetSelection: onSetSelection,
5232
      customSemanticsActions: customSemanticsActions,
5233 5234 5235 5236 5237
      hintOverrides: onTapHint != null || onLongPressHint != null ?
        new SemanticsHintOverrides(
          onTapHint: onTapHint,
          onLongPressHint: onLongPressHint,
        ) : null,
5238
    ),
5239 5240 5241 5242 5243 5244
  );

  /// Creates a semantic annotation using [SemanticsProperties].
  ///
  /// The [container] and [properties] arguments must not be null.
  const Semantics.fromProperties({
Hixie's avatar
Hixie committed
5245 5246
    Key key,
    Widget child,
5247 5248
    this.container = false,
    this.explicitChildNodes = false,
5249
    this.excludeSemantics = false,
5250
    @required this.properties,
5251
  }) : assert(container != null),
5252
       assert(properties != null),
5253
       super(key: key, child: child);
Hixie's avatar
Hixie committed
5254

5255 5256 5257 5258
  /// Contains properties used by assistive technologies to make the application
  /// more accessible.
  final SemanticsProperties properties;

5259
  /// If [container] is true, this widget will introduce a new
5260 5261
  /// node in the semantics tree. Otherwise, the semantics will be
  /// merged with the semantics of any ancestors (if the ancestor allows that).
5262
  ///
5263 5264 5265
  /// Whether descendants of this widget can add their semantic information to the
  /// [SemanticsNode] introduced by this configuration is controlled by
  /// [explicitChildNodes].
Hixie's avatar
Hixie committed
5266 5267
  final bool container;

5268 5269 5270 5271 5272 5273 5274 5275 5276 5277
  /// Whether descendants of this widget are allowed to add semantic information
  /// to the [SemanticsNode] annotated by this widget.
  ///
  /// When set to false descendants are allowed to annotate [SemanticNode]s of
  /// their parent with the semantic information they want to contribute to the
  /// semantic tree.
  /// When set to true the only way for descendants to contribute semantic
  /// information to the semantic tree is to introduce new explicit
  /// [SemanticNode]s to the tree.
  ///
5278 5279 5280 5281
  /// If the semantics properties of this node include
  /// [SemanticsProperties.scopesRoute] set to true, then [explicitChildNodes]
  /// must be true also.
  ///
5282 5283
  /// This setting is often used in combination with [SemanticsConfiguration.isSemanticBoundary]
  /// to create semantic boundaries that are either writable or not for children.
5284 5285
  final bool explicitChildNodes;

5286 5287 5288 5289 5290 5291 5292 5293 5294
  /// Whether to replace all child semantics with this node.
  ///
  /// Defaults to false.
  ///
  /// When this flag is set to true, all child semantics nodes are ignored.
  /// This can be used as a convenience for cases where a child is wrapped in
  /// an [ExcludeSemantics] widget and then another [Semantics] widget.
  final bool excludeSemantics;

5295
  @override
5296 5297 5298
  RenderSemanticsAnnotations createRenderObject(BuildContext context) {
    return new RenderSemanticsAnnotations(
      container: container,
5299
      explicitChildNodes: explicitChildNodes,
5300
      excludeSemantics: excludeSemantics,
5301
      enabled: properties.enabled,
5302
      checked: properties.checked,
5303
      toggled: properties.toggled,
5304 5305
      selected: properties.selected,
      button: properties.button,
5306 5307 5308
      header: properties.header,
      textField: properties.textField,
      focused: properties.focused,
5309
      liveRegion: properties.liveRegion,
5310
      inMutuallyExclusiveGroup: properties.inMutuallyExclusiveGroup,
5311
      obscured: properties.obscured,
5312 5313
      scopesRoute: properties.scopesRoute,
      namesRoute: properties.namesRoute,
5314
      hidden: properties.hidden,
5315
      image: properties.image,
5316 5317 5318 5319 5320
      label: properties.label,
      value: properties.value,
      increasedValue: properties.increasedValue,
      decreasedValue: properties.decreasedValue,
      hint: properties.hint,
5321
      hintOverrides: properties.hintOverrides,
Ian Hickson's avatar
Ian Hickson committed
5322
      textDirection: _getTextDirection(context),
5323
      sortKey: properties.sortKey,
5324 5325 5326 5327 5328 5329 5330 5331
      onTap: properties.onTap,
      onLongPress: properties.onLongPress,
      onScrollLeft: properties.onScrollLeft,
      onScrollRight: properties.onScrollRight,
      onScrollUp: properties.onScrollUp,
      onScrollDown: properties.onScrollDown,
      onIncrease: properties.onIncrease,
      onDecrease: properties.onDecrease,
5332
      onCopy: properties.onCopy,
5333
      onDismiss: properties.onDismiss,
5334 5335
      onCut: properties.onCut,
      onPaste: properties.onPaste,
5336 5337
      onMoveCursorForwardByCharacter: properties.onMoveCursorForwardByCharacter,
      onMoveCursorBackwardByCharacter: properties.onMoveCursorBackwardByCharacter,
5338 5339
      onMoveCursorForwardByWord: properties.onMoveCursorForwardByWord,
      onMoveCursorBackwardByWord: properties.onMoveCursorBackwardByWord,
5340
      onSetSelection: properties.onSetSelection,
5341 5342
      onDidGainAccessibilityFocus: properties.onDidGainAccessibilityFocus,
      onDidLoseAccessibilityFocus: properties.onDidLoseAccessibilityFocus,
5343
      customSemanticsActions: properties.customSemanticsActions,
5344 5345
    );
  }
Hixie's avatar
Hixie committed
5346

5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358
  TextDirection _getTextDirection(BuildContext context) {
    if (properties.textDirection != null)
      return properties.textDirection;

    final bool containsText = properties.label != null || properties.value != null || properties.hint != null;

    if (!containsText)
      return null;

    return Directionality.of(context);
  }

5359
  @override
5360
  void updateRenderObject(BuildContext context, RenderSemanticsAnnotations renderObject) {
5361 5362
    renderObject
      ..container = container
5363
      ..explicitChildNodes = explicitChildNodes
5364
      ..excludeSemantics = excludeSemantics
5365
      ..scopesRoute = properties.scopesRoute
5366
      ..enabled = properties.enabled
5367
      ..checked = properties.checked
5368
      ..toggled = properties.toggled
5369
      ..selected = properties.selected
5370 5371 5372 5373 5374 5375 5376
      ..button = properties.button
      ..header = properties.header
      ..textField = properties.textField
      ..focused = properties.focused
      ..inMutuallyExclusiveGroup = properties.inMutuallyExclusiveGroup
      ..obscured = properties.obscured
      ..hidden = properties.hidden
5377 5378
      ..image = properties.image
      ..liveRegion = properties.liveRegion
5379 5380 5381 5382 5383
      ..label = properties.label
      ..value = properties.value
      ..increasedValue = properties.increasedValue
      ..decreasedValue = properties.decreasedValue
      ..hint = properties.hint
5384
      ..hintOverrides = properties.hintOverrides
5385
      ..namesRoute = properties.namesRoute
5386
      ..textDirection = _getTextDirection(context)
5387
      ..sortKey = properties.sortKey
5388 5389 5390 5391 5392 5393 5394
      ..onTap = properties.onTap
      ..onLongPress = properties.onLongPress
      ..onScrollLeft = properties.onScrollLeft
      ..onScrollRight = properties.onScrollRight
      ..onScrollUp = properties.onScrollUp
      ..onScrollDown = properties.onScrollDown
      ..onIncrease = properties.onIncrease
5395
      ..onDismiss = properties.onDismiss
5396
      ..onDecrease = properties.onDecrease
5397 5398 5399
      ..onCopy = properties.onCopy
      ..onCut = properties.onCut
      ..onPaste = properties.onPaste
5400
      ..onMoveCursorForwardByCharacter = properties.onMoveCursorForwardByCharacter
5401
      ..onMoveCursorBackwardByCharacter = properties.onMoveCursorForwardByCharacter
5402 5403
      ..onMoveCursorForwardByWord = properties.onMoveCursorForwardByWord
      ..onMoveCursorBackwardByWord = properties.onMoveCursorBackwardByWord
5404 5405
      ..onSetSelection = properties.onSetSelection
      ..onDidGainAccessibilityFocus = properties.onDidGainAccessibilityFocus
5406 5407
      ..onDidLoseAccessibilityFocus = properties.onDidLoseAccessibilityFocus
      ..customSemanticsActions = properties.customSemanticsActions;
Hixie's avatar
Hixie committed
5408 5409
  }

5410
  @override
5411 5412 5413 5414 5415
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<bool>('container', container));
    properties.add(new DiagnosticsProperty<SemanticsProperties>('properties', this.properties));
    this.properties.debugFillProperties(properties);
Hixie's avatar
Hixie committed
5416 5417 5418
  }
}

5419 5420
/// A widget that merges the semantics of its descendants.
///
Hixie's avatar
Hixie committed
5421 5422
/// Causes all the semantics of the subtree rooted at this node to be
/// merged into one node in the semantics tree. For example, if you
5423
/// have a widget with a Text node next to a checkbox widget, this
Hixie's avatar
Hixie committed
5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437
/// could be used to merge the label from the Text node with the
/// "checked" semantic state of the checkbox into a single node that
/// had both the label and the checked state. Otherwise, the label
/// would be presented as a separate feature than the checkbox, and
/// the user would not be able to be sure that they were related.
///
/// Be aware that if two nodes in the subtree have conflicting
/// semantics, the result may be nonsensical. For example, a subtree
/// with a checked checkbox and an unchecked checkbox will be
/// presented as checked. All the labels will be merged into a single
/// string (with newlines separating each label from the other). If
/// multiple nodes in the merged subtree can handle semantic gestures,
/// the first one in tree order will be the one to receive the
/// callbacks.
5438
class MergeSemantics extends SingleChildRenderObjectWidget {
5439
  /// Creates a widget that merges the semantics of its descendants.
5440
  const MergeSemantics({ Key key, Widget child }) : super(key: key, child: child);
5441 5442

  @override
5443
  RenderMergeSemantics createRenderObject(BuildContext context) => new RenderMergeSemantics();
Hixie's avatar
Hixie committed
5444 5445
}

5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460
/// A widget that drops the semantics of all widget that were painted before it
/// in the same semantic container.
///
/// This is useful to hide widgets from accessibility tools that are painted
/// behind a certain widget, e.g. an alert should usually disallow interaction
/// with any widget located "behind" the alert (even when they are still
/// partially visible). Similarly, an open [Drawer] blocks interactions with
/// any widget outside the drawer.
///
/// See also:
///
/// * [ExcludeSemantics] which drops all semantics of its descendants.
class BlockSemantics extends SingleChildRenderObjectWidget {
  /// Creates a widget that excludes the semantics of all widgets painted before
  /// it in the same semantic container.
5461
  const BlockSemantics({ Key key, this.blocking = true, Widget child }) : super(key: key, child: child);
5462 5463 5464 5465 5466 5467 5468

  /// Whether this widget is blocking semantics of all widget that were painted
  /// before it in the same semantic container.
  final bool blocking;

  @override
  RenderBlockSemantics createRenderObject(BuildContext context) => new RenderBlockSemantics(blocking: blocking);
5469 5470

  @override
5471 5472 5473 5474 5475
  void updateRenderObject(BuildContext context, RenderBlockSemantics renderObject) {
    renderObject.blocking = blocking;
  }

  @override
5476 5477 5478
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<bool>('blocking', blocking));
5479
  }
5480 5481
}

5482
/// A widget that drops all the semantics of its descendants.
Hixie's avatar
Hixie committed
5483
///
5484 5485 5486
/// When [excluding] is true, this widget (and its subtree) is excluded from
/// the semantics tree.
///
5487
/// This can be used to hide descendant widgets that would otherwise be
Hixie's avatar
Hixie committed
5488 5489 5490
/// reported but that would only be confusing. For example, the
/// material library's [Chip] widget hides the avatar since it is
/// redundant with the chip label.
5491 5492 5493 5494
///
/// See also:
///
/// * [BlockSemantics] which drops semantics of widgets earlier in the tree.
5495
class ExcludeSemantics extends SingleChildRenderObjectWidget {
5496
  /// Creates a widget that drops all the semantics of its descendants.
5497 5498
  const ExcludeSemantics({
    Key key,
5499
    this.excluding = true,
5500 5501 5502 5503 5504 5505 5506 5507 5508
    Widget child,
  }) : assert(excluding != null),
        super(key: key, child: child);

  /// Whether this widget is excluded in the semantics tree.
  final bool excluding;

  @override
  RenderExcludeSemantics createRenderObject(BuildContext context) => new RenderExcludeSemantics(excluding: excluding);
5509 5510

  @override
5511 5512 5513 5514 5515
  void updateRenderObject(BuildContext context, RenderExcludeSemantics renderObject) {
    renderObject.excluding = excluding;
  }

  @override
5516 5517 5518
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(new DiagnosticsProperty<bool>('excluding', excluding));
5519
  }
Hixie's avatar
Hixie committed
5520 5521
}

5522
/// A widget that builds its child.
Adam Barth's avatar
Adam Barth committed
5523 5524
///
/// Useful for attaching a key to an existing widget.
5525
class KeyedSubtree extends StatelessWidget {
5526
  /// Creates a widget that builds its child.
5527
  const KeyedSubtree({
5528 5529
    Key key,
    @required this.child
5530 5531
  }) : assert(child != null),
       super(key: key);
5532

5533
  /// The widget below this widget in the tree.
5534 5535
  ///
  /// {@macro flutter.widgets.child}
5536 5537
  final Widget child;

Adam Barth's avatar
Adam Barth committed
5538 5539
  /// Creates a KeyedSubtree for child with a key that's based on the child's existing key or childIndex.
  factory KeyedSubtree.wrap(Widget child, int childIndex) {
5540
    final Key key = child.key != null ? new ValueKey<Key>(child.key) : new ValueKey<int>(childIndex);
Adam Barth's avatar
Adam Barth committed
5541 5542 5543
    return new KeyedSubtree(key: key, child: child);
  }

5544
  /// Wrap each item in a KeyedSubtree whose key is based on the item's existing key or
5545
  /// the sum of its list index and `baseIndex`.
5546
  static List<Widget> ensureUniqueKeysForList(Iterable<Widget> items, { int baseIndex = 0 }) {
5547 5548 5549
    if (items == null || items.isEmpty)
      return items;

5550
    final List<Widget> itemsWithUniqueKeys = <Widget>[];
5551
    int itemIndex = baseIndex;
Adam Barth's avatar
Adam Barth committed
5552 5553
    for (Widget item in items) {
      itemsWithUniqueKeys.add(new KeyedSubtree.wrap(item, itemIndex));
5554 5555 5556 5557
      itemIndex += 1;
    }

    assert(!debugItemsHaveDuplicateKeys(itemsWithUniqueKeys));
Hans Muller's avatar
Hans Muller committed
5558
    return itemsWithUniqueKeys;
5559 5560
  }

5561
  @override
5562
  Widget build(BuildContext context) => child;
Adam Barth's avatar
Adam Barth committed
5563
}
5564

5565
/// A platonic widget that calls a closure to obtain its child widget.
5566 5567 5568
///
/// See also:
///
5569
///  * [StatefulBuilder], a platonic widget which also has state.
5570
class Builder extends StatelessWidget {
5571 5572 5573
  /// Creates a widget that delegates its build to a callback.
  ///
  /// The [builder] argument must not be null.
5574
  const Builder({
5575 5576
    Key key,
    @required this.builder
5577 5578
  }) : assert(builder != null),
       super(key: key);
5579 5580 5581

  /// Called to obtain the child widget.
  ///
5582
  /// This function is called whenever this widget is included in its parent's
5583
  /// build and the old widget (if any) that it synchronizes with has a distinct
5584 5585 5586
  /// object identity. Typically the parent's build method will construct
  /// a new tree of widgets and so a new Builder child will not be [identical]
  /// to the corresponding old one.
5587
  final WidgetBuilder builder;
5588

5589
  @override
5590 5591 5592
  Widget build(BuildContext context) => builder(context);
}

5593 5594 5595
/// Signature for the builder callback used by [StatefulBuilder].
///
/// Call [setState] to schedule the [StatefulBuilder] to rebuild.
5596
typedef Widget StatefulWidgetBuilder(BuildContext context, StateSetter setState);
5597 5598 5599 5600 5601

/// A platonic widget that both has state and calls a closure to obtain its child widget.
///
/// See also:
///
5602
///  * [Builder], the platonic stateless widget.
5603
class StatefulBuilder extends StatefulWidget {
5604 5605 5606
  /// Creates a widget that both has state and delegates its build to a callback.
  ///
  /// The [builder] argument must not be null.
5607
  const StatefulBuilder({
5608 5609
    Key key,
    @required this.builder
5610 5611
  }) : assert(builder != null),
       super(key: key);
5612

5613 5614 5615 5616 5617 5618 5619
  /// Called to obtain the child widget.
  ///
  /// This function is called whenever this widget is included in its parent's
  /// build and the old widget (if any) that it synchronizes with has a distinct
  /// object identity. Typically the parent's build method will construct
  /// a new tree of widgets and so a new Builder child will not be [identical]
  /// to the corresponding old one.
5620
  final StatefulWidgetBuilder builder;
5621 5622

  @override
5623 5624
  _StatefulBuilderState createState() => new _StatefulBuilderState();
}
5625

5626
class _StatefulBuilderState extends State<StatefulBuilder> {
5627
  @override
5628
  Widget build(BuildContext context) => widget.builder(context, setState);
5629
}