blob: 0e124d450ee68d2950f4120beabe60c23cc0eb67 [file] [log] [blame]
// 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.
import 'dart:ui' as ui show Image, ImageFilter;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'debug.dart';
import 'framework.dart';
export 'package:flutter/animation.dart';
export 'package:flutter/foundation.dart' show
ChangeNotifier,
FlutterErrorDetails,
Listenable,
TargetPlatform,
ValueNotifier;
export 'package:flutter/painting.dart';
export 'package:flutter/rendering.dart' show
AlignmentTween,
AlignmentGeometryTween,
Axis,
BoxConstraints,
CrossAxisAlignment,
CustomClipper,
CustomPainter,
CustomPainterSemantics,
DecorationPosition,
FlexFit,
FlowDelegate,
FlowPaintingContext,
FractionalOffsetTween,
HitTestBehavior,
LayerLink,
MainAxisAlignment,
MainAxisSize,
MultiChildLayoutDelegate,
Overflow,
PaintingContext,
PointerCancelEvent,
PointerCancelEventListener,
PointerDownEvent,
PointerDownEventListener,
PointerEvent,
PointerMoveEvent,
PointerMoveEventListener,
PointerUpEvent,
PointerUpEventListener,
RelativeRect,
SemanticsBuilderCallback,
ShaderCallback,
SingleChildLayoutDelegate,
StackFit,
TextOverflow,
ValueChanged,
ValueGetter,
WrapAlignment,
WrapCrossAlignment;
// Examples can assume:
// class TestWidget extends StatelessWidget { @override Widget build(BuildContext context) => const Placeholder(); }
// WidgetTester tester;
// 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
bool updateShouldNotify(Directionality oldWidget) => textDirection != oldWidget.textDirection;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new EnumProperty<TextDirection>('textDirection', textDirection));
}
}
// PAINTING NODES
/// A widget that makes its child partially transparent.
///
/// This class paints its child into an intermediate buffer and then blends the
/// child back into the scene partially transparent.
///
/// 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.
///
/// ## 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.
///
/// See also:
///
/// * [ShaderMask], which can apply more elaborate effects to its child.
/// * [Transform], which applies an arbitrary transform to its child widget at
/// paint time.
class Opacity extends SingleChildRenderObjectWidget {
/// 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).
const Opacity({
Key key,
@required this.opacity,
Widget child,
}) : assert(opacity != null && opacity >= 0.0 && opacity <= 1.0),
super(key: key, child: child);
/// 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).
///
/// 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.
final double opacity;
@override
RenderOpacity createRenderObject(BuildContext context) => new RenderOpacity(opacity: opacity);
@override
void updateRenderObject(BuildContext context, RenderOpacity renderObject) {
renderObject.opacity = opacity;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DoubleProperty('opacity', opacity));
}
}
/// A widget that applies a mask generated by a [Shader] to its child.
///
/// For example, [ShaderMask] can be used to gradually fade out the edge
/// of a child by using a [new ui.Gradient.linear] mask.
///
/// ## Sample code
///
/// This example makes the text look like it is on fire:
///
/// ```dart
/// new ShaderMask(
/// shaderCallback: (Rect bounds) {
/// return new RadialGradient(
/// center: Alignment.topLeft,
/// 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.
/// * [BackdropFilter], which applies an image filter to the background.
class ShaderMask extends SingleChildRenderObjectWidget {
/// Creates a widget that applies a mask generated by a [Shader] to its child.
///
/// The [shaderCallback] and [blendMode] arguments must not be null.
const ShaderMask({
Key key,
@required this.shaderCallback,
this.blendMode: BlendMode.modulate,
Widget child
}) : assert(shaderCallback != null),
assert(blendMode != null),
super(key: key, child: child);
/// Called to create the [dart:ui.Shader] that generates the mask.
///
/// 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.
///
/// Typically this will use a [LinearGradient] or [RadialGradient] to create
/// the [dart:ui.Shader], though the [dart:ui.ImageShader] class could also be
/// used.
final ShaderCallback shaderCallback;
/// The [BlendMode] to use when applying the shader to the child.
///
/// 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;
@override
RenderShaderMask createRenderObject(BuildContext context) {
return new RenderShaderMask(
shaderCallback: shaderCallback,
blendMode: blendMode,
);
}
@override
void updateRenderObject(BuildContext context, RenderShaderMask renderObject) {
renderObject
..shaderCallback = shaderCallback
..blendMode = blendMode;
}
}
/// A widget that applies a filter to the existing painted content and then paints [child].
///
/// This effect is relatively expensive, especially if the filter is non-local,
/// such as a blur.
///
/// See also:
///
/// * [DecoratedBox], which draws a background under (or over) a widget.
/// * [Opacity], which changes the opacity of the widget itself.
class BackdropFilter extends SingleChildRenderObjectWidget {
/// Creates a backdrop filter.
///
/// The [filter] argument must not be null.
const BackdropFilter({
Key key,
@required this.filter,
Widget child
}) : assert(filter != null),
super(key: key, child: child);
/// The image filter to apply to the existing painted content before painting the child.
///
/// For example, consider using [ImageFilter.blur] to create a backdrop
/// blur effect
final ui.ImageFilter filter;
@override
RenderBackdropFilter createRenderObject(BuildContext context) {
return new RenderBackdropFilter(filter: filter);
}
@override
void updateRenderObject(BuildContext context, RenderBackdropFilter renderObject) {
renderObject.filter = filter;
}
}
/// A widget that provides a canvas on which to draw during the paint phase.
///
/// When asked to paint, [CustomPaint] first asks its [painter] to paint on the
/// current canvas, then it paints its child, and then, after painting its
/// child, it asks its [foregroundPainter] to paint. The coordinate system of the
/// canvas matches the coordinate system of the [CustomPaint] object. The
/// painters are expected to paint within a rectangle starting at the origin and
/// encompassing a region of the given size. (If the painters paint outside
/// those bounds, there might be insufficient memory allocated to rasterize the
/// painting commands and the resulting behavior is undefined.)
///
/// Painters are implemented by subclassing [CustomPainter].
///
/// 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
/// [Size.zero]. [size] must not be null.
///
/// [isComplex] and [willChange] are hints to the compositor's raster cache
/// and must not be null.
///
/// ## 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),
/// ),
/// ),
/// ),
/// )
/// ```
///
/// See also:
///
/// * [CustomPainter], the class to extend when creating custom painters.
/// * [Canvas], the class that a custom painter uses to paint.
class CustomPaint extends SingleChildRenderObjectWidget {
/// Creates a widget that delegates its painting.
const CustomPaint({
Key key,
this.painter,
this.foregroundPainter,
this.size: Size.zero,
this.isComplex: false,
this.willChange: false,
Widget child,
}) : assert(size != null),
assert(isComplex != null),
assert(willChange != null),
super(key: key, child: child);
/// The painter that paints before the children.
final CustomPainter painter;
/// The painter that paints after the children.
final CustomPainter foregroundPainter;
/// 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;
/// 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
/// frame. If this flag is not set, then the compositor will apply its own
/// 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;
@override
RenderCustomPaint createRenderObject(BuildContext context) {
return new RenderCustomPaint(
painter: painter,
foregroundPainter: foregroundPainter,
preferredSize: size,
isComplex: isComplex,
willChange: willChange,
);
}
@override
void updateRenderObject(BuildContext context, RenderCustomPaint renderObject) {
renderObject
..painter = painter
..foregroundPainter = foregroundPainter
..preferredSize = size
..isComplex = isComplex
..willChange = willChange;
}
@override
void didUnmountRenderObject(RenderCustomPaint renderObject) {
renderObject
..painter = null
..foregroundPainter = null;
}
}
/// A widget that clips its child using a rectangle.
///
/// By default, [ClipRect] prevents its child from painting outside its
/// bounds, but the size and location of the clip rect can be customized using a
/// custom [clipper].
///
/// [ClipRect] is commonly used with these widgets, which commonly paint outside
/// their bounds:
///
/// * [CustomPaint]
/// * [CustomSingleChildLayout]
/// * [CustomMultiChildLayout]
/// * [Align] and [Center] (e.g., if [Align.widthFactor] or
/// [Align.heightFactor] is less than 1.0).
/// * [OverflowBox]
/// * [SizedOverflowBox]
///
/// ## Sample code
///
/// For example, by combining a [ClipRect] with an [Align], one can show just
/// the top half of an [Image]:
///
/// ```dart
/// new ClipRect(
/// child: new Align(
/// alignment: Alignment.topCenter,
/// heightFactor: 0.5,
/// child: new Image.network(userAvatarUrl),
/// ),
/// )
/// ```
///
/// 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.
class ClipRect extends SingleChildRenderObjectWidget {
/// Creates a rectangular clip.
///
/// If [clipper] is null, the clip will match the layout size and position of
/// the child.
const ClipRect({ Key key, this.clipper, Widget child }) : super(key: key, child: child);
/// If non-null, determines which clip to use.
final CustomClipper<Rect> clipper;
@override
RenderClipRect createRenderObject(BuildContext context) => new RenderClipRect(clipper: clipper);
@override
void updateRenderObject(BuildContext context, RenderClipRect renderObject) {
renderObject.clipper = clipper;
}
@override
void didUnmountRenderObject(RenderClipRect renderObject) {
renderObject.clipper = null;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null));
}
}
/// A widget that clips its child using a rounded rectangle.
///
/// 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].
///
/// 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.
class ClipRRect extends SingleChildRenderObjectWidget {
/// Creates a rounded-rectangular clip.
///
/// The [borderRadius] defaults to [BorderRadius.zero], i.e. a rectangle with
/// right-angled corners.
///
/// If [clipper] is non-null, then [borderRadius] is ignored.
const ClipRRect({
Key key,
this.borderRadius,
this.clipper,
Widget child,
}) : assert(borderRadius != null || clipper != null),
super(key: key, child: child);
/// The border radius of the rounded corners.
///
/// Values are clamped so that horizontal and vertical radii sums do not
/// exceed width/height.
///
/// This value is ignored if [clipper] is non-null.
final BorderRadius borderRadius;
/// If non-null, determines which clip to use.
final CustomClipper<RRect> clipper;
@override
RenderClipRRect createRenderObject(BuildContext context) => new RenderClipRRect(borderRadius: borderRadius, clipper: clipper);
@override
void updateRenderObject(BuildContext context, RenderClipRRect renderObject) {
renderObject
..borderRadius = borderRadius
..clipper = clipper;
}
@override
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));
}
}
/// A widget that clips its child using an oval.
///
/// 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].
/// 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.
class ClipOval extends SingleChildRenderObjectWidget {
/// Creates an oval-shaped clip.
///
/// If [clipper] is null, the oval will be inscribed into the layout size and
/// position of the child.
const ClipOval({ Key key, this.clipper, Widget child }) : super(key: key, child: child);
/// If non-null, determines which clip to use.
///
/// 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.
final CustomClipper<Rect> clipper;
@override
RenderClipOval createRenderObject(BuildContext context) => new RenderClipOval(clipper: clipper);
@override
void updateRenderObject(BuildContext context, RenderClipOval renderObject) {
renderObject.clipper = clipper;
}
@override
void didUnmountRenderObject(RenderClipOval renderObject) {
renderObject.clipper = null;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null));
}
}
/// A widget that clips its child using a path.
///
/// Calls a callback on a delegate whenever the widget is to be
/// 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 {
/// 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.
const ClipPath({ Key key, this.clipper, Widget child }) : super(key: key, child: child);
/// 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;
@override
RenderClipPath createRenderObject(BuildContext context) => new RenderClipPath(clipper: clipper);
@override
void updateRenderObject(BuildContext context, RenderClipPath renderObject) {
renderObject.clipper = clipper;
}
@override
void didUnmountRenderObject(RenderClipPath renderObject) {
renderObject.clipper = null;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<CustomClipper<Path>>('clipper', clipper, defaultValue: null));
}
}
/// A widget representing a physical layer that clips its children to a shape.
///
/// Physical layers cast shadows based on an [elevation] which is nominally in
/// logical pixels, coming vertically out of the rendering surface.
///
/// For shapes that cannot be expressed as a rectangle with rounded corners use
/// [PhysicalShape].
///
/// See also:
///
/// * [DecoratedBox], which can apply more arbitrary shadow effects.
/// * [ClipRect], which applies a clip to its child.
class PhysicalModel extends SingleChildRenderObjectWidget {
/// Creates a physical model with a rounded-rectangular clip.
///
/// The [color] is required; physical things have a color.
///
/// The [shape], [elevation], [color], and [shadowColor] must not be null.
const PhysicalModel({
Key key,
this.shape: BoxShape.rectangle,
this.borderRadius,
this.elevation: 0.0,
@required this.color,
this.shadowColor: const Color(0xFF000000),
Widget child,
}) : assert(shape != null),
assert(elevation != null),
assert(color != null),
assert(shadowColor != null),
super(key: key, child: child);
/// The type of shape.
final BoxShape shape;
/// The border radius of the rounded corners.
///
/// Values are clamped so that horizontal and vertical radii sums do not
/// exceed width/height.
///
/// This is ignored if the [shape] is not [BoxShape.rectangle].
final BorderRadius borderRadius;
/// The z-coordinate at which to place this physical object.
final double elevation;
/// The background color.
final Color color;
/// The shadow color.
final Color shadowColor;
@override
RenderPhysicalModel createRenderObject(BuildContext context) {
return new RenderPhysicalModel(
shape: shape,
borderRadius: borderRadius,
elevation: elevation, color: color,
shadowColor: shadowColor,
);
}
@override
void updateRenderObject(BuildContext context, RenderPhysicalModel renderObject) {
renderObject
..shape = shape
..borderRadius = borderRadius
..elevation = elevation
..color = color
..shadowColor = shadowColor;
}
@override
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));
}
}
/// 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.
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,
this.elevation: 0.0,
@required this.color,
this.shadowColor: const Color(0xFF000000),
Widget child,
}) : assert(clipper != null),
assert(elevation != null),
assert(color != null),
assert(shadowColor != null),
super(key: key, child: child);
/// Determines which clip to use.
final CustomClipper<Path> clipper;
/// 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,
elevation: elevation,
color: color,
shadowColor: shadowColor
);
}
@override
void updateRenderObject(BuildContext context, RenderPhysicalShape renderObject) {
renderObject
..clipper = clipper
..elevation = elevation
..color = color
..shadowColor = shadowColor;
}
@override
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));
}
}
// POSITIONING AND SIZING NODES
/// A widget that applies a transformation before painting its child.
///
/// ## 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(
/// alignment: Alignment.topRight,
/// transform: new Matrix4.skewY(0.3)..rotateZ(-math.pi / 12.0),
/// child: new Container(
/// padding: const EdgeInsets.all(8.0),
/// color: const Color(0xFFE8581C),
/// child: const Text('Apartment for rent!'),
/// ),
/// ),
/// )
/// ```
///
/// See also:
///
/// * [RotatedBox], which rotates the child widget during layout, not just
/// during painting.
/// * [FractionalTranslation], which applies a translation to the child
/// that is relative to the child's size.
/// * [FittedBox], which sizes and positions its child widget to fit the parent
/// according to a given [BoxFit] discipline.
class Transform extends SingleChildRenderObjectWidget {
/// Creates a widget that transforms its child.
///
/// The [transform] argument must not be null.
const Transform({
Key key,
@required this.transform,
this.origin,
this.alignment,
this.transformHitTests: true,
Widget child,
}) : assert(transform != null),
super(key: key, child: child);
/// 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(
/// angle: -math.pi / 12.0,
/// 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,
this.alignment: Alignment.center,
this.transformHitTests: true,
Widget child,
}) : transform = new Matrix4.rotationZ(angle),
super(key: key, child: child);
/// 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,
this.transformHitTests: true,
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,
this.alignment: Alignment.center,
this.transformHitTests: true,
Widget child,
}) : transform = new Matrix4.diagonal3Values(scale, scale, 1.0),
super(key: key, child: child);
/// The matrix to transform the child by during painting.
final Matrix4 transform;
/// 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.
final Offset origin;
/// 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.
/// 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;
/// Whether to apply the transformation when performing hit tests.
final bool transformHitTests;
@override
RenderTransform createRenderObject(BuildContext context) {
return new RenderTransform(
transform: transform,
origin: origin,
alignment: alignment,
textDirection: Directionality.of(context),
transformHitTests: transformHitTests
);
}
@override
void updateRenderObject(BuildContext context, RenderTransform renderObject) {
renderObject
..transform = transform
..origin = origin
..alignment = alignment
..textDirection = Directionality.of(context)
..transformHitTests = transformHitTests;
}
}
/// A widget that can be targeted by a [CompositedTransformFollower].
///
/// 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,
this.showWhenUnlinked: true,
this.offset: Offset.zero,
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;
}
}
/// Scales and positions its child within itself according to [fit].
///
/// See also:
///
/// * [Transform], which applies an arbitrary transform to its child widget at
/// paint time.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
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.
const FittedBox({
Key key,
this.fit: BoxFit.contain,
this.alignment: Alignment.center,
Widget child,
}) : assert(fit != null),
assert(alignment != null),
super(key: key, child: child);
/// How to inscribe the child into the space allocated during layout.
final BoxFit fit;
/// How to align the child within its parent's bounds.
///
/// An alignment of (-1.0, -1.0) aligns the child to the top-left corner of its
/// parent's bounds. An alignment of (1.0, 0.0) aligns the child to the middle
/// of the right edge of its parent's bounds.
///
/// 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.
final AlignmentGeometry alignment;
@override
RenderFittedBox createRenderObject(BuildContext context) {
return new RenderFittedBox(
fit: fit,
alignment: alignment,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderFittedBox renderObject) {
renderObject
..fit = fit
..alignment = alignment
..textDirection = Directionality.of(context);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new EnumProperty<BoxFit>('fit', fit));
properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
}
}
/// 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.
///
/// See also:
///
/// * [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.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class FractionalTranslation extends SingleChildRenderObjectWidget {
/// Creates a widget that translates its child's painting.
///
/// The [translation] argument must not be null.
const FractionalTranslation({
Key key,
@required this.translation,
this.transformHitTests: true,
Widget child,
}) : assert(translation != null),
super(key: key, child: child);
/// 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;
/// Whether to apply the translation when performing hit tests.
final bool transformHitTests;
@override
RenderFractionalTranslation createRenderObject(BuildContext context) {
return new RenderFractionalTranslation(
translation: translation,
transformHitTests: transformHitTests,
);
}
@override
void updateRenderObject(BuildContext context, RenderFractionalTranslation renderObject) {
renderObject
..translation = translation
..transformHitTests = transformHitTests;
}
}
/// A widget that rotates its child by a integral number of quarter turns.
///
/// 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.
///
/// ## 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.
/// * [new Transform.rotate], which applies a rotation paint effect.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class RotatedBox extends SingleChildRenderObjectWidget {
/// A widget that rotates its child.
///
/// The [quarterTurns] argument must not be null.
const RotatedBox({
Key key,
@required this.quarterTurns,
Widget child,
}) : assert(quarterTurns != null),
super(key: key, child: child);
/// The number of clockwise quarter turns the child should be rotated.
final int quarterTurns;
@override
RenderRotatedBox createRenderObject(BuildContext context) => new RenderRotatedBox(quarterTurns: quarterTurns);
@override
void updateRenderObject(BuildContext context, RenderRotatedBox renderObject) {
renderObject.quarterTurns = quarterTurns;
}
}
/// A widget that insets its child by the given padding.
///
/// 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.
///
/// ## Sample code
///
/// This snippet indents the child (a [Card] with some [Text]) by eight pixels
/// in each direction:
///
/// ```dart
/// new Padding(
/// padding: new EdgeInsets.all(8.0),
/// child: const Card(child: const Text('Hello World!')),
/// )
/// ```
///
/// ## 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
/// mechanism for building up widgets.
///
/// See also:
///
/// * [EdgeInsets], the class that is used to describe the padding dimensions.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class Padding extends SingleChildRenderObjectWidget {
/// Creates a widget that insets its child.
///
/// The [padding] argument must not be null.
const Padding({
Key key,
@required this.padding,
Widget child,
}) : assert(padding != null),
super(key: key, child: child);
/// The amount of space by which to inset the child.
final EdgeInsetsGeometry padding;
@override
RenderPadding createRenderObject(BuildContext context) {
return new RenderPadding(
padding: padding,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderPadding renderObject) {
renderObject
..padding = padding
..textDirection = Directionality.of(context);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
}
}
/// A widget that aligns its child within itself and optionally sizes itself
/// based on the child's size.
///
/// 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,
/// with an alignment of [Alignment.bottomRight].
///
/// 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.
///
/// See also:
///
/// * [CustomSingleChildLayout], which uses a delegate to control the layout of
/// a single child.
/// * [Center], which is the same as [Align] but with the [alignment] always
/// set to [Alignment.center].
/// * [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/).
class Align extends SingleChildRenderObjectWidget {
/// Creates an alignment widget.
///
/// The alignment defaults to [Alignment.center].
const Align({
Key key,
this.alignment: Alignment.center,
this.widthFactor,
this.heightFactor,
Widget child
}) : assert(alignment != null),
assert(widthFactor == null || widthFactor >= 0.0),
assert(heightFactor == null || heightFactor >= 0.0),
super(key: key, child: child);
/// How to align the child.
///
/// The x and y values of the [Alignment] control the horizontal and vertical
/// alignment, respectively. An x value of -1.0 means that the left edge of
/// 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.
/// For example, a value of 0.0 means that the center of the child is aligned
/// with the center of the parent.
///
/// 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].
final AlignmentGeometry alignment;
/// If non-null, sets its width to the child's width multiplied by this factor.
///
/// Can be both greater and less than 1.0 but must be positive.
final double widthFactor;
/// If non-null, sets its height to the child's height multiplied by this factor.
///
/// Can be both greater and less than 1.0 but must be positive.
final double heightFactor;
@override
RenderPositionedBox createRenderObject(BuildContext context) {
return new RenderPositionedBox(
alignment: alignment,
widthFactor: widthFactor,
heightFactor: heightFactor,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderPositionedBox renderObject) {
renderObject
..alignment = alignment
..widthFactor = widthFactor
..heightFactor = heightFactor
..textDirection = Directionality.of(context);
}
@override
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));
}
}
/// A widget that centers its child within itself.
///
/// 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.
///
/// See also:
///
/// * [Align], which lets you arbitrarily position a child within itself,
/// rather than just centering it.
/// * [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/).
class Center extends Align {
/// Creates a widget that centers its child.
const Center({ Key key, double widthFactor, double heightFactor, Widget child })
: super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
}
/// A widget that defers the layout of its single child to a delegate.
///
/// 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.
///
/// See also:
///
/// * [SingleChildLayoutDelegate], which controls the layout of the child.
/// * [Align], which sizes itself based on its child's size and positions
/// the child according to an [Alignment] value.
/// * [FractionallySizedBox], which sizes its child based on a fraction of its own
/// size and positions the child according to an [Alignment] value.
/// * [CustomMultiChildLayout], which uses a delegate to position multiple
/// children.
class CustomSingleChildLayout extends SingleChildRenderObjectWidget {
/// Creates a custom single child layout.
///
/// The [delegate] argument must not be null.
const CustomSingleChildLayout({
Key key,
@required this.delegate,
Widget child
}) : assert(delegate != null),
super(key: key, child: child);
/// The delegate that controls the layout of the child.
final SingleChildLayoutDelegate delegate;
@override
RenderCustomSingleChildLayoutBox createRenderObject(BuildContext context) {
return new RenderCustomSingleChildLayoutBox(delegate: delegate);
}
@override
void updateRenderObject(BuildContext context, RenderCustomSingleChildLayoutBox renderObject) {
renderObject.delegate = delegate;
}
}
/// Metadata for identifying children in a [CustomMultiChildLayout].
///
/// The [MultiChildLayoutDelegate.hasChild],
/// [MultiChildLayoutDelegate.layoutChild], and
/// [MultiChildLayoutDelegate.positionChild] methods use these identifiers.
class LayoutId extends ParentDataWidget<CustomMultiChildLayout> {
/// Marks a child with a layout identifier.
///
/// Both the child and the id arguments must not be null.
LayoutId({
Key key,
@required this.id,
@required Widget child
}) : assert(child != null),
assert(id != null),
super(key: key ?? new ValueKey<Object>(id), child: child);
/// An object representing the identity of this child.
///
/// The [id] needs to be unique among the children that the
/// [CustomMultiChildLayout] manages.
final Object id;
@override
void applyParentData(RenderObject renderObject) {
assert(renderObject.parentData is MultiChildLayoutParentData);
final MultiChildLayoutParentData parentData = renderObject.parentData;
if (parentData.id != id) {
parentData.id = id;
final AbstractNode targetParent = renderObject.parent;
if (targetParent is RenderObject)
targetParent.markNeedsLayout();
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<Object>('id', id));
}
}
/// A widget that uses a delegate to size and position multiple children.
///
/// 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.
///
/// [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.
///
/// See also:
///
/// * [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.
class CustomMultiChildLayout extends MultiChildRenderObjectWidget {
/// Creates a custom multi-child layout.
///
/// The [delegate] argument must not be null.
CustomMultiChildLayout({
Key key,
@required this.delegate,
List<Widget> children: const <Widget>[],
}) : assert(delegate != null),
super(key: key, children: children);
/// The delegate that controls the layout of the children.
final MultiChildLayoutDelegate delegate;
@override
RenderCustomMultiChildLayoutBox createRenderObject(BuildContext context) {
return new RenderCustomMultiChildLayoutBox(delegate: delegate);
}
@override
void updateRenderObject(BuildContext context, RenderCustomMultiChildLayoutBox renderObject) {
renderObject.delegate = delegate;
}
}
/// A box with a specified size.
///
/// 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.
///
/// 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
/// [height] to [double.infinity].
///
/// ## 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.
/// * [UnconstrainedBox], a container that tries to let its child draw without
/// constraints.
/// * [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
/// constraints while also sizing its child to match a given aspect ratio.
/// * [FittedBox], which sizes and positions its child widget to fit the parent
/// according to a given [BoxFit] discipline.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class SizedBox extends SingleChildRenderObjectWidget {
/// 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.
const SizedBox({ Key key, this.width, this.height, Widget child })
: super(key: key, child: child);
/// Creates a box that will become as large as its parent allows.
const SizedBox.expand({ Key key, Widget child })
: width = double.infinity,
height = double.infinity,
super(key: key, child: child);
/// 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);
/// If non-null, requires the child to have exactly this width.
final double width;
/// If non-null, requires the child to have exactly this height.
final double height;
@override
RenderConstrainedBox createRenderObject(BuildContext context) {
return new RenderConstrainedBox(
additionalConstraints: _additionalConstraints,
);
}
BoxConstraints get _additionalConstraints {
return new BoxConstraints.tightFor(width: width, height: height);
}
@override
void updateRenderObject(BuildContext context, RenderConstrainedBox renderObject) {
renderObject.additionalConstraints = _additionalConstraints;
}
@override
String toStringShort() {
final String type = (width == double.infinity && height == double.infinity) ?
'$runtimeType.expand' : '$runtimeType';
return key == null ? '$type' : '$type-$key';
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final DiagnosticLevel level = (width == double.infinity && height == double.infinity)
? DiagnosticLevel.hidden
: DiagnosticLevel.info;
properties.add(new DoubleProperty('width', width, defaultValue: null, level: level));
properties.add(new DoubleProperty('height', height, defaultValue: null, level: level));
}
}
/// A widget that imposes additional constraints on its child.
///
/// For example, if you wanted [child] to have a minimum height of 50.0 logical
/// pixels, you could use `const BoxConstraints(minHeight: 50.0)` as the
/// [constraints].
///
/// ## 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!')),
/// )
/// ```
///
/// The same behavior can be obtained using the [new SizedBox.expand] widget.
///
/// See also:
///
/// * [BoxConstraints], the class that describes constraints.
/// * [UnconstrainedBox], a container that tries to let its child draw without
/// constraints.
/// * [SizedBox], which lets you specify tight constraints by explicitly
/// specifying the height or width.
/// * [FractionallySizedBox], which sizes its child based on a fraction of its
/// own size and positions the child according to an [Alignment] value.
/// * [AspectRatio], a widget that attempts to fit within the parent's
/// constraints while also sizing its child to match a given aspect ratio.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class ConstrainedBox extends SingleChildRenderObjectWidget {
/// 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
}) : assert(constraints != null),
assert(constraints.debugAssertIsValid()),
super(key: key, child: child);
/// The additional constraints to impose on the child.
final BoxConstraints constraints;
@override
RenderConstrainedBox createRenderObject(BuildContext context) {
return new RenderConstrainedBox(additionalConstraints: constraints);
}
@override
void updateRenderObject(BuildContext context, RenderConstrainedBox renderObject) {
renderObject.additionalConstraints = constraints;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<BoxConstraints>('constraints', constraints, showName: false));
}
}
/// 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
/// 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.
///
/// 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:
///
/// * [ConstrainedBox], for a box which imposes constraints on its child.
/// * [Align], which loosens the constraints given to the child rather than
/// removing them entirely.
/// * [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,
this.alignment: Alignment.center,
this.constrainedAxis,
}) : 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;
/// The axis to retain constraints on, if any.
///
/// If not set, or set to null (the default), neither axis will retain its
/// constraints. If set to [Axis.vertical], then vertical constraints will
/// be retained, and if set to [Axis.horizontal], then horizontal constraints
/// will be retained.
final Axis constrainedAxis;
@override
void updateRenderObject(BuildContext context, covariant RenderUnconstrainedBox renderObject) {
renderObject
..textDirection = textDirection ?? Directionality.of(context)
..alignment = alignment
..constrainedAxis = constrainedAxis;
}
@override
RenderUnconstrainedBox createRenderObject(BuildContext context) => new RenderUnconstrainedBox(
textDirection: textDirection ?? Directionality.of(context),
alignment: alignment,
constrainedAxis: constrainedAxis,
);
@override
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));
}
}
/// A widget that sizes its child to a fraction of the total available space.
/// For more details about the layout algorithm, see
/// [RenderFractionallySizedOverflowBox].
///
/// See also:
///
/// * [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/).
class FractionallySizedBox extends SingleChildRenderObjectWidget {
/// 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.
const FractionallySizedBox({
Key key,
this.alignment: Alignment.center,
this.widthFactor,
this.heightFactor,
Widget child,
}) : assert(alignment != null),
assert(widthFactor == null || widthFactor >= 0.0),
assert(heightFactor == null || heightFactor >= 0.0),
super(key: key, child: child);
/// If non-null, the fraction of the incoming width given to the child.
///
/// If non-null, the child is given a tight width constraint that is the max
/// incoming width constraint multiplied by this factor.
///
/// If null, the incoming width constraints are passed to the child
/// unmodified.
final double widthFactor;
/// If non-null, the fraction of the incoming height given to the child.
///
/// If non-null, the child is given a tight height constraint that is the max
/// incoming height constraint multiplied by this factor.
///
/// If null, the incoming height constraints are passed to the child
/// unmodified.
final double heightFactor;
/// How to align the child.
///
/// The x and y values of the alignment control the horizontal and vertical
/// alignment, respectively. An x value of -1.0 means that the left edge of
/// 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.
/// For example, a value of 0.0 means that the center of the child is aligned
/// with the center of the parent.
///
/// 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.
final AlignmentGeometry alignment;
@override
RenderFractionallySizedOverflowBox createRenderObject(BuildContext context) {
return new RenderFractionallySizedOverflowBox(
alignment: alignment,
widthFactor: widthFactor,
heightFactor: heightFactor,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderFractionallySizedOverflowBox renderObject) {
renderObject
..alignment = alignment
..widthFactor = widthFactor
..heightFactor = heightFactor
..textDirection = Directionality.of(context);
}
@override
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));
}
}
/// 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
/// 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).
///
/// 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.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class LimitedBox extends SingleChildRenderObjectWidget {
/// 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.
const LimitedBox({
Key key,
this.maxWidth: double.infinity,
this.maxHeight: double.infinity,
Widget child,
}) : assert(maxWidth != null && maxWidth >= 0.0),
assert(maxHeight != null && maxHeight >= 0.0),
super(key: key, child: child);
/// The maximum width limit to apply in the absence of a
/// [BoxConstraints.maxWidth] constraint.
final double maxWidth;
/// The maximum height limit to apply in the absence of a
/// [BoxConstraints.maxHeight] constraint.
final double maxHeight;
@override
RenderLimitedBox createRenderObject(BuildContext context) {
return new RenderLimitedBox(
maxWidth: maxWidth,
maxHeight: maxHeight
);
}
@override
void updateRenderObject(BuildContext context, RenderLimitedBox renderObject) {
renderObject
..maxWidth = maxWidth
..maxHeight = maxHeight;
}
@override
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));
}
}
/// A widget that imposes different constraints on its child than it gets
/// from its parent, possibly allowing the child to overflow the parent.
///
/// 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/).
class OverflowBox extends SingleChildRenderObjectWidget {
/// Creates a widget that lets its child overflow itself.
const OverflowBox({
Key key,
this.alignment: Alignment.center,
this.minWidth,
this.maxWidth,
this.minHeight,
this.maxHeight,
Widget child,
}) : super(key: key, child: child);
/// How to align the child.
///
/// The x and y values of the alignment control the horizontal and vertical
/// alignment, respectively. An x value of -1.0 means that the left edge of
/// 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.
/// For example, a value of 0.0 means that the center of the child is aligned
/// with the center of the parent.
///
/// 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.
final AlignmentGeometry alignment;
/// The minimum width constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
final double minWidth;
/// The maximum width constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
final double maxWidth;
/// The minimum height constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
final double minHeight;
/// The maximum height constraint to give the child. Set this to null (the
/// default) to use the constraint from the parent instead.
final double maxHeight;
@override
RenderConstrainedOverflowBox createRenderObject(BuildContext context) {
return new RenderConstrainedOverflowBox(
alignment: alignment,
minWidth: minWidth,
maxWidth: maxWidth,
minHeight: minHeight,
maxHeight: maxHeight,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderConstrainedOverflowBox renderObject) {
renderObject
..alignment = alignment
..minWidth = minWidth
..maxWidth = maxWidth
..minHeight = minHeight
..maxHeight = maxHeight
..textDirection = Directionality.of(context);
}
@override
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));
}
}
/// A widget that is a specific size but passes its original constraints
/// 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/).
class SizedOverflowBox extends SingleChildRenderObjectWidget {
/// Creates a widget of a given size that lets its child overflow.
///
/// The [size] argument must not be null.
const SizedOverflowBox({
Key key,
@required this.size,
this.alignment: Alignment.center,
Widget child,
}) : assert(size != null),
assert(alignment != null),
super(key: key, child: child);
/// How to align the child.
///
/// The x and y values of the alignment control the horizontal and vertical
/// alignment, respectively. An x value of -1.0 means that the left edge of
/// 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.
/// For example, a value of 0.0 means that the center of the child is aligned
/// with the center of the parent.
///
/// 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.
final AlignmentGeometry alignment;
/// The size this widget should attempt to be.
final Size size;
@override
RenderSizedOverflowBox createRenderObject(BuildContext context) {
return new RenderSizedOverflowBox(
alignment: alignment,
requestedSize: size,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderSizedOverflowBox renderObject) {
renderObject
..alignment = alignment
..requestedSize = size
..textDirection = Directionality.of(context);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
properties.add(new DiagnosticsProperty<Size>('size', size, defaultValue: null));
}
}
/// 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.
///
/// See also:
///
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class Offstage extends SingleChildRenderObjectWidget {
/// Creates a widget that visually hides its child.
const Offstage({ Key key, this.offstage: true, Widget child })
: assert(offstage != null),
super(key: key, child: child);
/// 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
RenderOffstage createRenderObject(BuildContext context) => new RenderOffstage(offstage: offstage);
@override
void updateRenderObject(BuildContext context, RenderOffstage renderObject) {
renderObject.offstage = offstage;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<bool>('offstage', offstage));
}
@override
_OffstageElement createElement() => new _OffstageElement(this);
}
class _OffstageElement extends SingleChildRenderObjectElement {
_OffstageElement(Offstage widget) : super(widget);
@override
Offstage get widget => super.widget;
@override
void debugVisitOnstageChildren(ElementVisitor visitor) {
if (!widget.offstage)
super.debugVisitOnstageChildren(visitor);
}
}
/// A widget that attempts to size the child to a specific aspect ratio.
///
/// The widget first tries the largest width permitted by the layout
/// 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.
///
/// 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/).
class AspectRatio extends SingleChildRenderObjectWidget {
/// Creates a widget with a specific aspect ratio.
///
/// The [aspectRatio] argument must not be null.
const AspectRatio({
Key key,
@required this.aspectRatio,
Widget child
}) : assert(aspectRatio != null),
super(key: key, child: child);
/// The aspect ratio to attempt to use.
///
/// 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.
final double aspectRatio;
@override
RenderAspectRatio createRenderObject(BuildContext context) => new RenderAspectRatio(aspectRatio: aspectRatio);
@override
void updateRenderObject(BuildContext context, RenderAspectRatio renderObject) {
renderObject.aspectRatio = aspectRatio;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DoubleProperty('aspectRatio', aspectRatio));
}
}
/// A widget that sizes its child to the child's intrinsic width.
///
/// 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.
///
/// 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.
///
/// See also:
///
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class IntrinsicWidth extends SingleChildRenderObjectWidget {
/// Creates a widget that sizes its child to the child's intrinsic width.
///
/// This class is relatively expensive. Avoid using it where possible.
const IntrinsicWidth({ Key key, this.stepWidth, this.stepHeight, Widget child })
: super(key: key, child: child);
/// If non-null, force the child's width to be a multiple of this value.
final double stepWidth;
/// If non-null, force the child's height to be a multiple of this value.
final double stepHeight;
@override
RenderIntrinsicWidth createRenderObject(BuildContext context) {
return new RenderIntrinsicWidth(stepWidth: stepWidth, stepHeight: stepHeight);
}
@override
void updateRenderObject(BuildContext context, RenderIntrinsicWidth renderObject) {
renderObject
..stepWidth = stepWidth
..stepHeight = stepHeight;
}
}
/// A widget that sizes its child to the child's intrinsic height.
///
/// 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.
///
/// 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.
///
/// See also:
///
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class IntrinsicHeight extends SingleChildRenderObjectWidget {
/// Creates a widget that sizes its child to the child's intrinsic height.
///
/// This class is relatively expensive. Avoid using it where possible.
const IntrinsicHeight({ Key key, Widget child }) : super(key: key, child: child);
@override
RenderIntrinsicHeight createRenderObject(BuildContext context) => new RenderIntrinsicHeight();
}
/// 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
/// 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.
///
/// 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/).
class Baseline extends SingleChildRenderObjectWidget {
/// Creates a widget that positions its child according to the child's baseline.
///
/// The [baseline] and [baselineType] arguments must not be null.
const Baseline({
Key key,
@required this.baseline,
@required this.baselineType,
Widget child
}) : assert(baseline != null),
assert(baselineType != null),
super(key: key, child: child);
/// 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.
final TextBaseline baselineType;
@override
RenderBaseline createRenderObject(BuildContext context) {
return new RenderBaseline(baseline: baseline, baselineType: baselineType);
}
@override
void updateRenderObject(BuildContext context, RenderBaseline renderObject) {
renderObject
..baseline = baseline
..baselineType = baselineType;
}
}
// SLIVERS
/// 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],
/// [SliverFixedExtentList], [SliverPrototypeExtentList], or [SliverGrid],
/// which are more efficient because they instantiate only those children that
/// are actually visible through the scroll view's viewport.
///
/// 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.
/// * [SliverPrototypeExtentList], which displays multiple box widgets with the
/// same main-axis extent as a prototype item, in a linear array.
/// * [SliverGrid], which displays multiple box widgets in arbitrary positions.
class SliverToBoxAdapter extends SingleChildRenderObjectWidget {
/// Creates a sliver that contains a single box widget.
const SliverToBoxAdapter({
Key key,
Widget child,
}) : super(key: key, child: child);
@override
RenderSliverToBoxAdapter createRenderObject(BuildContext context) => new RenderSliverToBoxAdapter();
}
/// 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
/// 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.
///
/// See also:
///
/// * [CustomScrollView], which displays a scrollable list of slivers.
class SliverPadding extends SingleChildRenderObjectWidget {
/// Creates a sliver that applies padding on each side of another sliver.
///
/// The [padding] argument must not be null.
const SliverPadding({
Key key,
@required this.padding,
Widget sliver,
}) : assert(padding != null),
super(key: key, child: sliver);
/// The amount of space by which to inset the child sliver.
final EdgeInsetsGeometry padding;
@override
RenderSliverPadding createRenderObject(BuildContext context) {
return new RenderSliverPadding(
padding: padding,
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderSliverPadding renderObject) {
renderObject
..padding = padding
..textDirection = Directionality.of(context);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(new DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
}
}
// LAYOUT NODES
/// 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;
}
/// A widget that arranges its children sequentially along a given axis, forcing
/// them to the dimension of the parent in the other axis.
///
/// This widget is rarely used directly. Instead, consider using [ListView],
/// 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.
///
/// 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.
///
/// By default, the [mainAxis] is [Axis.vertical].
ListBody({
Key key,
this.mainAxis: Axis.vertical,
this.reverse: false,
List<Widget> children: const <Widget>[],
}) : assert(mainAxis != null),
super(key: key, children: children);
/// The direction to use as the main axis.
final Axis mainAxis;
/// 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);
}
@override
RenderListBody createRenderObject(BuildContext context) {
return new RenderListBody(axisDirection: _getDirection(context));
}
@override
void updateRenderObject(BuildContext context, RenderListBody renderObject) {
renderObject.axisDirection = _getDirection(context);
}
}
/// A widget that positions its children relative to the edges of its box.
///
/// 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.
///
/// 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]
/// (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.
///
/// 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.
///
/// 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.
///
/// See also:
///
/// * [Align], which sizes itself based on its child's size and positions
/// the child according to an [Alignment] value.
/// * [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.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class Stack extends MultiChildRenderObjectWidget {
/// Creates a stack layout widget.
///
/// By default, the non-positioned children of the stack are aligned by their
/// top left corners.
Stack({
Key key,
this.alignment: AlignmentDirectional.topStart,
this.textDirection,
this.fit: StackFit.loose,
this.overflow: Overflow.clip,
List<Widget> children: const <Widget>[],
}) : super(key: key, children: children);
/// How to align the non-positioned and partially-positioned children in the
/// stack.
///
/// The non-positioned children are placed relative to each other such that
/// the points determined by [alignment] are co-located. For example, if the
/// [alignment] is [Alignment.topLeft], then the top left corner of
/// each non-positioned child will be located at the same global coordinate.
///
/// 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.
///
/// 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.
final AlignmentGeometry alignment;
/// The text direction with which to resolve [alignment].
///
/// Defaults to the ambient [Directionality].
final TextDirection textDirection;
/// 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]).
final StackFit fit;
/// Whether overflowing children should be clipped. See [Overflow].
///
/// Some children in a stack might overflow its box. When this flag is set to
/// [Overflow.clip], children cannot paint outside of the stack's box.
final Overflow overflow;
@override
RenderStack createRenderObject(BuildContext context) {
return new RenderStack(
alignment: alignment,
textDirection: textDirection ?? Directionality.of(context),
fit: fit,
overflow: overflow,
);
}
@override
void updateRenderObject(BuildContext context, RenderStack renderObject) {
renderObject
..alignment = alignment
..textDirection = textDirection ?? Directionality.of(context)
..fit = fit
..overflow = overflow;
}
@override
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));
}
}
/// A [Stack] that shows a single child from a list of children.
///
/// 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.
///
/// See also:
///
/// * [Stack], for more details about stacks.
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class IndexedStack extends Stack {
/// Creates a [Stack] widget that paints a single child.
///
/// The [index] argument must not be null.
IndexedStack({
Key key,
AlignmentGeometry alignment: AlignmentDirectional.topStart,
TextDirection textDirection,
StackFit sizing: StackFit.loose,
this.index: 0,
List<Widget> children: const <Widget>[],
}) : super(key: key, alignment: alignment, textDirection: textDirection, fit: sizing, children: children);
/// The index of the child to show.
final int index;
@override
RenderIndexedStack createRenderObject(BuildContext context) {
return new RenderIndexedStack(
index: index,
alignment: alignment,
textDirection: textDirection ?? Directionality.of(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderIndexedStack renderObject) {
renderObject
..index = index
..alignment = alignment
..textDirection = textDirection ?? Directionality.of(context);
}
}
/// A widget that controls where a child of a [Stack] is positioned.
///
/// 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).
///
/// 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]).
///
/// 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.
///
/// See also:
///
/// * [PositionedDirectional], which adapts to the ambient [Directionality].
class Positioned extends ParentDataWidget<Stack> {
/// Creates a widget that controls where a child of a [Stack] is positioned.
///
/// 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.
///
/// See also:
///
/// * [Positioned.directional], which specifies the widget's horizontal
/// position using `start` and `end` rather than `left` and `right`.
/// * [PositionedDirectional], which is similar to [Positioned.directional]
/// but adapts to the ambient [Directionality].
const Positioned({
Key key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
@required Widget child,
}) : assert(left == null || right == null || width == null),
assert(top == null || bottom == null || height == null),
super(key: key, child: child);
/// 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.
Positioned.fromRect({
Key key,
Rect rect,
@required Widget child,
}) : left = rect.left,
top = rect.top,
width = rect.width,
height = rect.height,
right = null,
bottom = null,
super(key: key, child: child);
/// 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);
/// Creates a Positioned object with [left], [top], [right], and [bottom] set
/// to 0.0 unless a value for them is passed.
const Positioned.fill({
Key key,
this.left: 0.0,
this.top: 0.0,
this.right: 0.0,
this.bottom: 0.0,
@required Widget child,
}) : width = null,
height = null,
super(key: key, child: child);
/// 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,
);
}
/// 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.
///
/// If all three are null, the [Stack.alignment] is used to position the child
/// horizontally.
final double left;
/// 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.
///
/// If all three are null, the [Stack.alignment] is used to position the child
/// vertically.
final double top;
/// 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.
///
/// If all three are null, the [Stack.alignment] is used to position the child
/// horizontally.
final double right;
/// 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.
///
/// If all three are null, the [Stack.alignment] is used to position the child
/// vertically.
final double bottom;
/// The child's width.
///
/// Only two out of the three horizontal values ([left], [right], [width]) can be
/// set. The third must be null.
///
/// If all three are null, the [Stack.alignment] is used to position the child
/// horizontally.
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.
///
/// If all three are null, the [Stack.alignment] is used to position the child
/// vertically.
final double height;
@override
void applyParentData(RenderObject renderObject) {
assert(renderObject.parentData is StackParentData);
final StackParentData parentData = renderObject.parentData;
bool needsLayout = false;
if (parentData.left != left) {
parentData.left = left;
needsLayout = true;
}
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;
}
if (parentData.width != width) {
parentData.width = width;
needsLayout = true;
}
if (parentData.height != height) {
parentData.height = height;
needsLayout = true;
}
if (needsLayout) {
final AbstractNode targetParent = renderObject.parent;
if (targetParent is RenderObject)
targetParent.markNeedsLayout();
}
}
@override
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));
}
}
/// 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.
///
/// {@macro flutter.widgets.child}
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,
);
}
}
/// A widget that displays its children in a one-dimensional array.
///
/// 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
/// horizontal) or [Column] (if it's vertical) instead, because that will be less
/// verbose.
///
/// To cause a child to expand to fill the available vertical space, wrap the
/// child in an [Expanded] widget.
///
/// 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
/// insufficient room, consider using a [ListView].
///
/// If you only have one child, then rather than using [Flex], [Row], or
/// [Column], consider using [Align] or [Center] to position the child.
///
/// ## Layout algorithm
///
/// _This section describes how a [Flex] is rendered by the framework._
/// _See [BoxConstraints] for an introduction to box layout models._
///
/// 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.
///
/// 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
/// that may be sized smaller (leaving some remaining room unused).
/// * The [catalog of layout widgets](https://flutter.io/widgets/layout/).
class Flex extends MultiChildRenderObjectWidget {
/// Creates a flex layout.
///
/// The [direction] is required.
///
/// The [direction], [mainAxisAlignment], [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 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.
Flex({
Key key,
@required this.direction,
this.mainAxisAlignment: MainAxisAlignment.start,
this.mainAxisSize: MainAxisSize.max,
this.crossAxisAlignment: CrossAxisAlignment.center,
this.textDirection,
this.verticalDirection: VerticalDirection.down,
this.textBaseline,
List<Widget> children: const <Widget>[],
}) : assert(direction != null),
assert(mainAxisAlignment != null),
assert(mainAxisSize != null),
assert(crossAxisAlignment != null),
assert(verticalDirection != null),
assert(crossAxisAlignment != CrossAxisAlignment.baseline || textBaseline != null),
super(key: key, children: children);
/// The direction to use as the main axis.
///
/// 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.)
final Axis direction;
/// How the children should be placed along the main axis.
///
/// 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.
final MainAxisAlignment mainAxisAlignment;
/// How much space should be occupied in the main axis.
///
/// After allocating space to children, there might be some remaining free
/// space. This value controls whether to maximize or minimize the amount of
/// free space, subject to the incoming layout constraints.
///
/// 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.
final MainAxisSize mainAxisSize;
/// How the children should be placed along the cross axis.
///
/// For example, [CrossAxisAlignment.center], the default, centers the
/// children in the cross axis (e.g., horizontally for a [Column]).
final CrossAxisAlignment crossAxisAlignment;
/// 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 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
/// [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;
/// If aligning items according to their baseline, which baseline to use.
final TextBaseline textBaseline;
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);
}
@override
RenderFlex createRenderObject(BuildContext context) {
return new RenderFlex(
direction: direction,
mainAxisAlignment: mainAxisAlignment,
mainAxisSize: mainAxisSize,
crossAxisAlignment: crossAxisAlignment,
textDirection: getEffectiveTextDirection(context),
verticalDirection: verticalDirection,
textBaseline: textBaseline,
);
}
@override
void updateRenderObject(BuildContext context, covariant RenderFlex renderObject) {
renderObject
..direction = direction
..mainAxisAlignment = mainAxisAlignment
..mainAxisSize = mainAxisSize
..crossAxisAlignment = crossAxisAlignment
..textDirection = getEffectiveTextDirection(context)
..verticalDirection = verticalDirection
..textBaseline = textBaseline;
}
@override
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));
}
}
/// A widget that displays its children in a horizontal array.
///
/// To cause a child to expand to fill the available horizontal space, wrap the
/// child in an [Expanded] widget.
///
/// 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
/// insufficient room, consider using a [ListView].
///
/// For a vertical variant, see [Column].
///
/// If you only have one child, then consider using [Align] or [Center] to
/// position the child.
///
/// ## 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(),
/// ),
/// ),
/// ],
/// )
/// ```
///
/// ## Troubleshooting
///
/// ### Why does my row have a yellow and black warning stripe?
///
/// 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.
///
/// #### 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