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

import 'package:flutter/rendering.dart';

7
import 'basic.dart';
8
import 'debug.dart';
9 10 11 12 13 14
import 'framework.dart';

export 'package:flutter/rendering.dart' show
  AxisDirection,
  GrowthDirection;

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/// A widget that is bigger on the inside.
///
/// [Viewport] is the visual workhorse of the scrolling machinery. It displays a
/// subset of its children according to its own dimensions and the given
/// [offset]. As the offset varies, different children are visible through
/// the viewport.
///
/// [Viewport] hosts a bidirectional list of slivers, anchored on a [center]
/// sliver, which is placed at the zero scroll offset. The center widget is
/// displayed in the viewport according to the [anchor] property.
///
/// Slivers that are earlier in the child list than [center] are displayed in
/// reverse order in the reverse [axisDirection] starting from the [center]. For
/// example, if the [axisDirection] is [AxisDirection.down], the first sliver
/// before [center] is placed above the [center]. The slivers that are later in
/// the child list than [center] are placed in order in the [axisDirection]. For
Yegor's avatar
Yegor committed
31
/// example, in the preceding scenario, the first sliver after [center] is
32 33 34 35 36 37 38 39 40 41 42 43 44 45
/// placed below the [center].
///
/// [Viewport] cannot contain box children directly. Instead, use a
/// [SliverList], [SliverFixedExtentList], [SliverGrid], or a
/// [SliverToBoxAdapter], for example.
///
/// See also:
///
///  * [ListView], [PageView], [GridView], and [CustomScrollView], which combine
///    [Scrollable] and [Viewport] into widgets that are easier to use.
///  * [SliverToBoxAdapter], which allows a box widget to be placed inside a
///    sliver context (the opposite of this widget).
///  * [ShrinkWrappingViewport], a variant of [Viewport] that shrink-wraps its
///    contents along the main axis.
Adam Barth's avatar
Adam Barth committed
46
class Viewport extends MultiChildRenderObjectWidget {
47 48 49 50 51 52
  /// Creates a widget that is bigger on the inside.
  ///
  /// The viewport listens to the [offset], which means you do not need to
  /// rebuild this widget when the [offset] changes.
  ///
  /// The [offset] argument must not be null.
53 54 55
  ///
  /// The [cacheExtent] must be specified if the [cacheExtentStyle] is
  /// not [CacheExtentStyle.pixel].
Adam Barth's avatar
Adam Barth committed
56
  Viewport({
57
    Key? key,
58
    this.axisDirection = AxisDirection.down,
59
    this.crossAxisDirection,
60
    this.anchor = 0.0,
61
    required this.offset,
62
    this.center,
63
    this.cacheExtent,
64
    this.cacheExtentStyle = CacheExtentStyle.pixel,
65
    this.clipBehavior = Clip.hardEdge,
66
    List<Widget> slivers = const <Widget>[],
67 68 69
  }) : assert(offset != null),
       assert(slivers != null),
       assert(center == null || slivers.where((Widget child) => child.key == center).length == 1),
70 71
       assert(cacheExtentStyle != null),
       assert(cacheExtentStyle != CacheExtentStyle.viewport || cacheExtent != null),
72
       assert(clipBehavior != null),
73
       super(key: key, children: slivers);
74

75
  /// The direction in which the [offset]'s [ViewportOffset.pixels] increases.
76 77 78 79
  ///
  /// For example, if the [axisDirection] is [AxisDirection.down], a scroll
  /// offset of zero is at the top of the viewport and increases towards the
  /// bottom of the viewport.
80
  final AxisDirection axisDirection;
81

82 83 84 85 86 87 88 89 90
  /// The direction in which child should be laid out in the cross axis.
  ///
  /// If the [axisDirection] is [AxisDirection.down] or [AxisDirection.up], this
  /// property defaults to [AxisDirection.left] if the ambient [Directionality]
  /// is [TextDirection.rtl] and [AxisDirection.right] if the ambient
  /// [Directionality] is [TextDirection.ltr].
  ///
  /// If the [axisDirection] is [AxisDirection.left] or [AxisDirection.right],
  /// this property defaults to [AxisDirection.down].
91
  final AxisDirection? crossAxisDirection;
92

93 94 95 96 97 98 99
  /// The relative position of the zero scroll offset.
  ///
  /// For example, if [anchor] is 0.5 and the [axisDirection] is
  /// [AxisDirection.down] or [AxisDirection.up], then the zero scroll offset is
  /// vertically centered within the viewport. If the [anchor] is 1.0, and the
  /// [axisDirection] is [AxisDirection.right], then the zero scroll offset is
  /// on the left edge of the viewport.
100
  final double anchor;
101 102 103 104 105 106 107 108 109

  /// Which part of the content inside the viewport should be visible.
  ///
  /// The [ViewportOffset.pixels] value determines the scroll offset that the
  /// viewport uses to select which part of its content to display. As the user
  /// scrolls the viewport, this value changes, which changes the content that
  /// is displayed.
  ///
  /// Typically a [ScrollPosition].
110
  final ViewportOffset offset;
111 112 113 114 115 116 117 118

  /// The first child in the [GrowthDirection.forward] growth direction.
  ///
  /// Children after [center] will be placed in the [axisDirection] relative to
  /// the [center]. Children before [center] will be placed in the opposite of
  /// the [axisDirection] relative to the [center].
  ///
  /// The [center] must be the key of a child of the viewport.
119
  final Key? center;
120

121
  /// {@macro flutter.rendering.RenderViewportBase.cacheExtent}
122 123 124 125
  ///
  /// See also:
  ///
  ///  * [cacheExtentStyle], which controls the units of the [cacheExtent].
126
  final double? cacheExtent;
127

128
  /// {@macro flutter.rendering.RenderViewportBase.cacheExtentStyle}
129 130
  final CacheExtentStyle cacheExtentStyle;

131
  /// {@macro flutter.material.Material.clipBehavior}
132
  ///
133
  /// Defaults to [Clip.hardEdge].
134 135
  final Clip clipBehavior;

136 137 138 139 140 141 142 143 144
  /// Given a [BuildContext] and an [AxisDirection], determine the correct cross
  /// axis direction.
  ///
  /// This depends on the [Directionality] if the `axisDirection` is vertical;
  /// otherwise, the default cross axis direction is downwards.
  static AxisDirection getDefaultCrossAxisDirection(BuildContext context, AxisDirection axisDirection) {
    assert(axisDirection != null);
    switch (axisDirection) {
      case AxisDirection.up:
145 146 147 148 149
        assert(debugCheckHasDirectionality(
          context,
          why: 'to determine the cross-axis direction when the viewport has an \'up\' axisDirection',
          alternative: 'Alternatively, consider specifying the \'crossAxisDirection\' argument on the Viewport.',
        ));
150
        return textDirectionToAxisDirection(Directionality.of(context));
151 152 153
      case AxisDirection.right:
        return AxisDirection.down;
      case AxisDirection.down:
154 155 156 157 158
        assert(debugCheckHasDirectionality(
          context,
          why: 'to determine the cross-axis direction when the viewport has a \'down\' axisDirection',
          alternative: 'Alternatively, consider specifying the \'crossAxisDirection\' argument on the Viewport.',
        ));
159
        return textDirectionToAxisDirection(Directionality.of(context));
160 161 162 163 164
      case AxisDirection.left:
        return AxisDirection.down;
    }
  }

165
  @override
Adam Barth's avatar
Adam Barth committed
166
  RenderViewport createRenderObject(BuildContext context) {
167
    return RenderViewport(
168
      axisDirection: axisDirection,
169
      crossAxisDirection: crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection),
170 171
      anchor: anchor,
      offset: offset,
172
      cacheExtent: cacheExtent,
173
      cacheExtentStyle: cacheExtentStyle,
174
      clipBehavior: clipBehavior,
175 176 177 178
    );
  }

  @override
Adam Barth's avatar
Adam Barth committed
179
  void updateRenderObject(BuildContext context, RenderViewport renderObject) {
180 181
    renderObject
      ..axisDirection = axisDirection
182
      ..crossAxisDirection = crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection)
183
      ..anchor = anchor
184
      ..offset = offset
185
      ..cacheExtent = cacheExtent
186 187
      ..cacheExtentStyle = cacheExtentStyle
      ..clipBehavior = clipBehavior;
188 189 190
  }

  @override
191
  MultiChildRenderObjectElement createElement() => _ViewportElement(this);
192 193

  @override
194 195
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
196 197 198 199
    properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
    properties.add(EnumProperty<AxisDirection>('crossAxisDirection', crossAxisDirection, defaultValue: null));
    properties.add(DoubleProperty('anchor', anchor));
    properties.add(DiagnosticsProperty<ViewportOffset>('offset', offset));
200
    if (center != null) {
201
      properties.add(DiagnosticsProperty<Key>('center', center));
202
    } else if (children.isNotEmpty && children.first.key != null) {
203
      properties.add(DiagnosticsProperty<Key>('center', children.first.key, tooltip: 'implicit'));
204
    }
205 206
    properties.add(DiagnosticsProperty<double>('cacheExtent', cacheExtent));
    properties.add(DiagnosticsProperty<CacheExtentStyle>('cacheExtentStyle', cacheExtentStyle));
207 208 209
  }
}

210
class _ViewportElement extends MultiChildRenderObjectElement {
211
  /// Creates an element that uses the given widget as its configuration.
212
  _ViewportElement(Viewport widget) : super(widget);
213 214

  @override
215
  Viewport get widget => super.widget as Viewport;
216 217

  @override
218
  RenderViewport get renderObject => super.renderObject as RenderViewport;
219 220

  @override
221
  void mount(Element? parent, Object? newSlot) {
222
    super.mount(parent, newSlot);
223
    _updateCenter();
224 225 226 227 228
  }

  @override
  void update(MultiChildRenderObjectWidget newWidget) {
    super.update(newWidget);
229
    _updateCenter();
230 231
  }

232
  void _updateCenter() {
233 234 235
    // TODO(ianh): cache the keys to make this faster
    if (widget.center != null) {
      renderObject.center = children.singleWhere(
236
        (Element element) => element.widget.key == widget.center,
237
      ).renderObject as RenderSliver?;
238
    } else if (children.isNotEmpty) {
239
      renderObject.center = children.first.renderObject as RenderSliver?;
240 241 242 243
    } else {
      renderObject.center = null;
    }
  }
244 245 246

  @override
  void debugVisitOnstageChildren(ElementVisitor visitor) {
247
    children.where((Element e) {
248
      final RenderSliver renderSliver = e.renderObject! as RenderSliver;
249
      return renderSliver.geometry!.visible;
250
    }).forEach(visitor);
251
  }
252
}
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
/// A widget that is bigger on the inside and shrink wraps its children in the
/// main axis.
///
/// [ShrinkWrappingViewport] displays a subset of its children according to its
/// own dimensions and the given [offset]. As the offset varies, different
/// children are visible through the viewport.
///
/// [ShrinkWrappingViewport] differs from [Viewport] in that [Viewport] expands
/// to fill the main axis whereas [ShrinkWrappingViewport] sizes itself to match
/// its children in the main axis. This shrink wrapping behavior is expensive
/// because the children, and hence the viewport, could potentially change size
/// whenever the [offset] changes (e.g., because of a collapsing header).
///
/// [ShrinkWrappingViewport] cannot contain box children directly. Instead, use
/// a [SliverList], [SliverFixedExtentList], [SliverGrid], or a
/// [SliverToBoxAdapter], for example.
///
/// See also:
///
///  * [ListView], [PageView], [GridView], and [CustomScrollView], which combine
///    [Scrollable] and [ShrinkWrappingViewport] into widgets that are easier to
///    use.
///  * [SliverToBoxAdapter], which allows a box widget to be placed inside a
///    sliver context (the opposite of this widget).
278
///  * [Viewport], a viewport that does not shrink-wrap its contents.
279
class ShrinkWrappingViewport extends MultiChildRenderObjectWidget {
280 281 282 283 284 285 286
  /// Creates a widget that is bigger on the inside and shrink wraps its
  /// children in the main axis.
  ///
  /// The viewport listens to the [offset], which means you do not need to
  /// rebuild this widget when the [offset] changes.
  ///
  /// The [offset] argument must not be null.
287
  ShrinkWrappingViewport({
288
    Key? key,
289
    this.axisDirection = AxisDirection.down,
290
    this.crossAxisDirection,
291
    required this.offset,
292
    this.clipBehavior = Clip.hardEdge,
293
    List<Widget> slivers = const <Widget>[],
294 295
  }) : assert(offset != null),
       super(key: key, children: slivers);
296

297
  /// The direction in which the [offset]'s [ViewportOffset.pixels] increases.
298 299 300 301
  ///
  /// For example, if the [axisDirection] is [AxisDirection.down], a scroll
  /// offset of zero is at the top of the viewport and increases towards the
  /// bottom of the viewport.
302
  final AxisDirection axisDirection;
303

304 305 306 307 308 309 310 311 312
  /// The direction in which child should be laid out in the cross axis.
  ///
  /// If the [axisDirection] is [AxisDirection.down] or [AxisDirection.up], this
  /// property defaults to [AxisDirection.left] if the ambient [Directionality]
  /// is [TextDirection.rtl] and [AxisDirection.right] if the ambient
  /// [Directionality] is [TextDirection.ltr].
  ///
  /// If the [axisDirection] is [AxisDirection.left] or [AxisDirection.right],
  /// this property defaults to [AxisDirection.down].
313
  final AxisDirection? crossAxisDirection;
314

315 316 317 318 319 320 321 322
  /// Which part of the content inside the viewport should be visible.
  ///
  /// The [ViewportOffset.pixels] value determines the scroll offset that the
  /// viewport uses to select which part of its content to display. As the user
  /// scrolls the viewport, this value changes, which changes the content that
  /// is displayed.
  ///
  /// Typically a [ScrollPosition].
323 324
  final ViewportOffset offset;

325
  /// {@macro flutter.material.Material.clipBehavior}
326 327 328 329
  ///
  /// Defaults to [Clip.hardEdge].
  final Clip clipBehavior;

330 331
  @override
  RenderShrinkWrappingViewport createRenderObject(BuildContext context) {
332
    return RenderShrinkWrappingViewport(
333
      axisDirection: axisDirection,
334
      crossAxisDirection: crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection),
335
      offset: offset,
336
      clipBehavior: clipBehavior,
337 338 339 340 341 342 343
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderShrinkWrappingViewport renderObject) {
    renderObject
      ..axisDirection = axisDirection
344
      ..crossAxisDirection = crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection)
345 346
      ..offset = offset
      ..clipBehavior = clipBehavior;
347 348 349
  }

  @override
350 351
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
352 353 354
    properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
    properties.add(EnumProperty<AxisDirection>('crossAxisDirection', crossAxisDirection, defaultValue: null));
    properties.add(DiagnosticsProperty<ViewportOffset>('offset', offset));
355 356
  }
}