single_child_scroll_view.dart 21.6 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2017 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:math' as math;

import 'package:flutter/rendering.dart';
8
import 'package:flutter/gestures.dart' show DragStartBehavior;
9 10 11

import 'basic.dart';
import 'framework.dart';
12
import 'primary_scroll_controller.dart';
13 14
import 'scroll_controller.dart';
import 'scroll_physics.dart';
15 16
import 'scrollable.dart';

17 18 19 20 21 22 23 24 25 26
/// A box in which a single widget can be scrolled.
///
/// This widget is useful when you have a single box that will normally be
/// entirely visible, for example a clock face in a time picker, but you need to
/// make sure it can be scrolled if the container gets too small in one axis
/// (the scroll direction).
///
/// It is also useful if you need to shrink-wrap in both axes (the main
/// scrolling direction as well as the cross axis), as one might see in a dialog
/// or pop-up menu. In that case, you might pair the [SingleChildScrollView]
27
/// with a [ListBody] child.
28 29 30 31
///
/// When you have a list of children and do not require cross-axis
/// shrink-wrapping behavior, for example a scrolling list that is always the
/// width of the screen, consider [ListView], which is vastly more efficient
32
/// that a [SingleChildScrollView] containing a [ListBody] or [Column] with
33 34
/// many children.
///
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
/// ## Sample code: Using [SingleChildScrollView] with a [Column]
///
/// Sometimes a layout is designed around the flexible properties of a
/// [Column], but there is the concern that in some cases, there might not
/// be enough room to see the entire contents. This could be because some
/// devices have unusually small screens, or because the application can
/// be used in landscape mode where the aspect ratio isn't what was
/// originally envisioned, or because the application is being shown in a
/// small window in split-screen mode. In any case, as a result, it might
/// make sense to wrap the layout in a [SingleChildScrollView].
///
/// Simply doing so, however, usually results in a conflict between the [Column],
/// which typically tries to grow as big as it can, and the [SingleChildScrollView],
/// which provides its children with an infinite amount of space.
///
/// To resolve this apparent conflict, there are a couple of techniques, as
/// discussed below. These techniques should only be used when the content is
/// normally expected to fit on the screen, so that the lazy instantiation of
/// a sliver-based [ListView] or [CustomScrollView] is not expected to provide
/// any performance benefit. If the viewport is expected to usually contain
/// content beyond the dimensions of the screen, then [SingleChildScrollView]
/// would be very expensive.
///
/// ### Centering, spacing, or aligning fixed-height content
///
/// If the content has fixed (or intrinsic) dimensions but needs to be spaced out,
/// centered, or otherwise positioned using the [Flex] layout model of a [Column],
/// the following technique can be used to provide the [Column] with a minimum
/// dimension while allowing it to shrink-wrap the contents when there isn't enough
/// room to apply these spacing or alignment needs.
///
/// A [LayoutBuilder] is used to obtain the size of the viewport (implicitly via
/// the constraints that the [SingleChildScrollView] sees, since viewports
/// typically grow to fit their maximum height constraint). Then, inside the
/// scroll view, a [ConstrainedBox] is used to set the minimum height of the
/// [Column].
///
/// The [Column] has no [Expanded] children, so rather than take on the infinite
/// height from its [BoxConstraints.maxHeight], (the viewport provides no maximum height
/// constraint), it automatically tries to shrink to fit its children. It cannot
/// be smaller than its [BoxConstraints.minHeight], though, and It therefore
/// becomes the bigger of the minimum height provided by the
/// [ConstrainedBox] and the sum of the heights of the children.
///
/// If the children aren't enough to fit that minimum size, the [Column] ends up
/// with some remaining space to allocate as specified by its
/// [Column.mainAxisAlignment] argument.
///
/// In this example, the children are spaced out equally, unless there's no
/// more room, in which case they stack vertically and scroll.
///
/// ```dart
87
/// LayoutBuilder(
88 89
///   builder: (BuildContext context, BoxConstraints viewportConstraints) {
///     return SingleChildScrollView(
90 91
///       child: ConstrainedBox(
///         constraints: BoxConstraints(
92 93
///           minHeight: viewportConstraints.maxHeight,
///         ),
94
///         child: Column(
95 96 97
///           mainAxisSize: MainAxisSize.min,
///           mainAxisAlignment: MainAxisAlignment.spaceAround,
///           children: <Widget>[
98
///             Container(
99 100 101 102
///               // A fixed-height child.
///               color: Colors.yellow,
///               height: 120.0,
///             ),
103
///             Container(
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
///               // Another fixed-height child.
///               color: Colors.green,
///               height: 120.0,
///             ),
///           ],
///         ),
///       ),
///     );
///   },
/// )
/// ```
///
/// When using this technique, [Expanded] and [Flexible] are not useful, because
/// in both cases the "available space" is infinite (since this is in a viewport).
/// The next section describes a technique for providing a maximum height constraint.
///
/// ### Expanding content to fit the viewport
///
/// The following example builds on the previous one. In addition to providing a
/// minimum dimension for the child [Column], an [IntrinsicHeight] widget is used
/// to force the column to be exactly as big as its contents. This constraint
/// combines with the [ConstrainedBox] constraints discussed previously to ensure
/// that the column becomes either as big as viewport, or as big as the contents,
/// whichever is biggest.
///
/// Both constraints must be used to get the desired effect. If only the
/// [IntrinsicHeight] was specified, then the column would not grow to fit the
/// entire viewport when its children were smaller than the whole screen. If only
/// the size of the viewport was used, then the [Column] would overflow if the
/// children were bigger than the viewport.
///
/// The widget that is to grow to fit the remaining space so provided is wrapped
/// in an [Expanded] widget.
///
/// ```dart
139
/// LayoutBuilder(
140 141
///   builder: (BuildContext context, BoxConstraints viewportConstraints) {
///     return SingleChildScrollView(
142 143
///       child: ConstrainedBox(
///         constraints: BoxConstraints(
144 145
///           minHeight: viewportConstraints.maxHeight,
///         ),
146 147
///         child: IntrinsicHeight(
///           child: Column(
148
///             children: <Widget>[
149
///               Container(
150 151 152 153
///                 // A fixed-height child.
///                 color: Colors.yellow,
///                 height: 120.0,
///               ),
154
///               Expanded(
155 156
///                 // A flexible child that will grow to fit the viewport but
///                 // still be at least as big as necessary to fit its contents.
157
///                 child: Container(
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
///                   color: Colors.blue,
///                   height: 120.0,
///                 ),
///               ),
///             ],
///           ),
///         ),
///       ),
///     );
///   },
/// )
/// ```
///
/// This technique is quite expensive, as it more or less requires that the contents
/// of the viewport be laid out twice (once to find their intrinsic dimensions, and
/// once to actually lay them out). The number of widgets within the column should
/// therefore be kept small. Alternatively, subsets of the children that have known
/// dimensions can be wrapped in a [SizedBox] that has tight vertical constraints,
/// so that the intrinsic sizing algorithm can short-circuit the computation when it
/// reaches those parts of the subtree.
///
179 180
/// See also:
///
181 182 183 184
///  * [ListView], which handles multiple children in a scrolling list.
///  * [GridView], which handles multiple children in a scrolling grid.
///  * [PageView], for a scrollable that works page by page.
///  * [Scrollable], which handles arbitrary scrolling effects.
185
class SingleChildScrollView extends StatelessWidget {
186
  /// Creates a box in which a single widget can be scrolled.
187
  const SingleChildScrollView({
188
    Key key,
189 190
    this.scrollDirection = Axis.vertical,
    this.reverse = false,
191
    this.padding,
192
    bool primary,
193 194
    this.physics,
    this.controller,
195
    this.child,
196
    this.dragStartBehavior = DragStartBehavior.start,
197
  }) : assert(scrollDirection != null),
198
       assert(dragStartBehavior != null),
199 200 201 202
       assert(!(controller != null && primary == true),
          'Primary ScrollViews obtain their ScrollController via inheritance from a PrimaryScrollController widget. '
          'You cannot both set primary to true and pass an explicit controller.'
       ),
203
       primary = primary ?? controller == null && identical(scrollDirection, Axis.vertical),
204
       super(key: key);
205

206 207 208
  /// The axis along which the scroll view scrolls.
  ///
  /// Defaults to [Axis.vertical].
209 210
  final Axis scrollDirection;

211 212 213 214 215 216 217
  /// Whether the scroll view scrolls in the reading direction.
  ///
  /// For example, if the reading direction is left-to-right and
  /// [scrollDirection] is [Axis.horizontal], then the scroll view scrolls from
  /// left to right when [reverse] is false and from right to left when
  /// [reverse] is true.
  ///
218
  /// Similarly, if [scrollDirection] is [Axis.vertical], then the scroll view
219 220 221 222
  /// scrolls from top to bottom when [reverse] is false and from bottom to top
  /// when [reverse] is true.
  ///
  /// Defaults to false.
223 224
  final bool reverse;

225
  /// The amount of space by which to inset the child.
226
  final EdgeInsetsGeometry padding;
227

228 229 230 231
  /// An object that can be used to control the position to which this scroll
  /// view is scrolled.
  ///
  /// Must be null if [primary] is true.
232 233 234 235 236 237 238 239
  ///
  /// A [ScrollController] serves several purposes. It can be used to control
  /// the initial scroll position (see [ScrollController.initialScrollOffset]).
  /// It can be used to control whether the scroll view should automatically
  /// save and restore its scroll position in the [PageStorage] (see
  /// [ScrollController.keepScrollOffset]). It can be used to read the current
  /// scroll position (see [ScrollController.offset]), or change it (see
  /// [ScrollController.animateTo]).
240 241
  final ScrollController controller;

242 243 244 245 246 247
  /// Whether this is the primary scroll view associated with the parent
  /// [PrimaryScrollController].
  ///
  /// On iOS, this identifies the scroll view that will scroll to top in
  /// response to a tap in the status bar.
  ///
248
  /// Defaults to true when [scrollDirection] is vertical and [controller] is
249
  /// not specified.
250 251
  final bool primary;

252 253 254 255 256 257
  /// How the scroll view should respond to user input.
  ///
  /// For example, determines how the scroll view continues to animate after the
  /// user stops dragging the scroll view.
  ///
  /// Defaults to matching platform conventions.
258 259
  final ScrollPhysics physics;

260
  /// The widget that scrolls.
261 262
  ///
  /// {@macro flutter.widgets.child}
263 264
  final Widget child;

265 266 267
  /// {@macro flutter.widgets.scrollable.dragStartBehavior}
  final DragStartBehavior dragStartBehavior;

268
  AxisDirection _getDirection(BuildContext context) {
269
    return getAxisDirectionFromAxisReverseAndDirectionality(context, scrollDirection, reverse);
270 271 272 273
  }

  @override
  Widget build(BuildContext context) {
274
    final AxisDirection axisDirection = _getDirection(context);
275 276
    Widget contents = child;
    if (padding != null)
277
      contents = Padding(padding: padding, child: contents);
278
    final ScrollController scrollController = primary
279 280
        ? PrimaryScrollController.of(context)
        : controller;
281
    final Scrollable scrollable = Scrollable(
282
      dragStartBehavior: dragStartBehavior,
283
      axisDirection: axisDirection,
284
      controller: scrollController,
285
      physics: physics,
286
      viewportBuilder: (BuildContext context, ViewportOffset offset) {
287
        return _SingleChildViewport(
288 289
          axisDirection: axisDirection,
          offset: offset,
290
          child: contents,
291 292
        );
      },
293
    );
294
    return primary && scrollController != null
295
      ? PrimaryScrollController.none(child: scrollable)
296
      : scrollable;
297 298 299 300
  }
}

class _SingleChildViewport extends SingleChildRenderObjectWidget {
301
  const _SingleChildViewport({
302
    Key key,
303
    this.axisDirection = AxisDirection.down,
304 305
    this.offset,
    Widget child,
306 307
  }) : assert(axisDirection != null),
       super(key: key, child: child);
308 309 310 311 312 313

  final AxisDirection axisDirection;
  final ViewportOffset offset;

  @override
  _RenderSingleChildViewport createRenderObject(BuildContext context) {
314
    return _RenderSingleChildViewport(
315 316 317 318 319 320 321 322 323 324 325 326 327 328
      axisDirection: axisDirection,
      offset: offset,
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderSingleChildViewport renderObject) {
    // Order dependency: The offset setter reads the axis direction.
    renderObject
      ..axisDirection = axisDirection
      ..offset = offset;
  }
}

329
class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMixin<RenderBox> implements RenderAbstractViewport {
330
  _RenderSingleChildViewport({
331
    AxisDirection axisDirection = AxisDirection.down,
332
    @required ViewportOffset offset,
333
    double cacheExtent = RenderAbstractViewport.defaultCacheExtent,
334
    RenderBox child,
335 336
  }) : assert(axisDirection != null),
       assert(offset != null),
337
       assert(cacheExtent != null),
338
       _axisDirection = axisDirection,
339 340
       _offset = offset,
       _cacheExtent = cacheExtent {
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    this.child = child;
  }

  AxisDirection get axisDirection => _axisDirection;
  AxisDirection _axisDirection;
  set axisDirection(AxisDirection value) {
    assert(value != null);
    if (value == _axisDirection)
      return;
    _axisDirection = value;
    markNeedsLayout();
  }

  Axis get axis => axisDirectionToAxis(axisDirection);

  ViewportOffset get offset => _offset;
  ViewportOffset _offset;
  set offset(ViewportOffset value) {
    assert(value != null);
    if (value == _offset)
      return;
    if (attached)
363
      _offset.removeListener(_hasScrolled);
364 365
    _offset = value;
    if (attached)
366
      _offset.addListener(_hasScrolled);
367
    markNeedsLayout();
368 369
  }

370 371 372 373 374 375 376 377 378 379 380
  /// {@macro flutter.rendering.viewport.cacheExtent}
  double get cacheExtent => _cacheExtent;
  double _cacheExtent;
  set cacheExtent(double value) {
    assert(value != null);
    if (value == _cacheExtent)
      return;
    _cacheExtent = value;
    markNeedsLayout();
  }

381 382 383 384 385
  void _hasScrolled() {
    markNeedsPaint();
    markNeedsSemanticsUpdate();
  }

386 387 388 389 390
  @override
  void setupParentData(RenderObject child) {
    // We don't actually use the offset argument in BoxParentData, so let's
    // avoid allocating it at all.
    if (child.parentData is! ParentData)
391
      child.parentData = ParentData();
392 393 394 395 396
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
397
    _offset.addListener(_hasScrolled);
398 399 400 401
  }

  @override
  void detach() {
402
    _offset.removeListener(_hasScrolled);
403 404 405 406 407 408
    super.detach();
  }

  @override
  bool get isRepaintBoundary => true;

409
  double get _viewportExtent {
410 411 412 413
    assert(hasSize);
    switch (axis) {
      case Axis.horizontal:
        return size.width;
414 415
      case Axis.vertical:
        return size.height;
416 417 418 419 420 421 422 423 424 425 426 427 428
    }
    return null;
  }

  double get _minScrollExtent {
    assert(hasSize);
    return 0.0;
  }

  double get _maxScrollExtent {
    assert(hasSize);
    if (child == null)
      return 0.0;
429 430 431 432 433 434 435
    switch (axis) {
      case Axis.horizontal:
        return math.max(0.0, child.size.width - size.width);
      case Axis.vertical:
        return math.max(0.0, child.size.height - size.height);
    }
    return null;
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  }

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
    switch (axis) {
      case Axis.horizontal:
        return constraints.heightConstraints();
      case Axis.vertical:
        return constraints.widthConstraints();
    }
    return null;
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    if (child != null)
      return child.getMinIntrinsicWidth(height);
    return 0.0;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    if (child != null)
      return child.getMaxIntrinsicWidth(height);
    return 0.0;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    if (child != null)
      return child.getMinIntrinsicHeight(width);
    return 0.0;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    if (child != null)
      return child.getMaxIntrinsicHeight(width);
    return 0.0;
  }

  // We don't override computeDistanceToActualBaseline(), because we
  // want the default behavior (returning null). Otherwise, as you
  // scroll, it would shift in its parent if the parent was baseline-aligned,
  // which makes no sense.

  @override
  void performLayout() {
    if (child == null) {
      size = constraints.smallest;
    } else {
      child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
      size = constraints.constrain(child.size);
    }

490
    offset.applyViewportDimension(_viewportExtent);
491 492 493
    offset.applyContentDimensions(_minScrollExtent, _maxScrollExtent);
  }

494 495 496
  Offset get _paintOffset => _paintOffsetForPosition(offset.pixels);

  Offset _paintOffsetForPosition(double position) {
497 498 499
    assert(axisDirection != null);
    switch (axisDirection) {
      case AxisDirection.up:
500
        return Offset(0.0, position - child.size.height + size.height);
501
      case AxisDirection.down:
502
        return Offset(0.0, -position);
503
      case AxisDirection.left:
504
        return Offset(position - child.size.width + size.width, 0.0);
505
      case AxisDirection.right:
506
        return Offset(-position, 0.0);
507 508 509 510 511 512 513 514 515 516 517 518
    }
    return null;
  }

  bool _shouldClipAtPaintOffset(Offset paintOffset) {
    assert(child != null);
    return paintOffset < Offset.zero || !(Offset.zero & size).contains((paintOffset & child.size).bottomRight);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (child != null) {
519
      final Offset paintOffset = _paintOffset;
520 521 522 523 524 525

      void paintContents(PaintingContext context, Offset offset) {
        context.paintChild(child, offset + paintOffset);
      }

      if (_shouldClipAtPaintOffset(paintOffset)) {
526
        context.pushClipRect(needsCompositing, offset, Offset.zero & size, paintContents);
527 528 529 530 531 532 533 534
      } else {
        paintContents(context, offset);
      }
    }
  }

  @override
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
535
    final Offset paintOffset = _paintOffset;
536 537 538 539 540
    transform.translate(paintOffset.dx, paintOffset.dy);
  }

  @override
  Rect describeApproximatePaintClip(RenderObject child) {
541
    if (child != null && _shouldClipAtPaintOffset(_paintOffset))
542
      return Offset.zero & size;
543 544 545 546
    return null;
  }

  @override
547
  bool hitTestChildren(HitTestResult result, { Offset position }) {
548
    if (child != null) {
549
      final Offset transformed = position + -_paintOffset;
550 551 552 553
      return child.hitTest(result, position: transformed);
    }
    return false;
  }
554 555

  @override
556 557
  RevealedOffset getOffsetToReveal(RenderObject target, double alignment, {Rect rect}) {
    rect ??= target.paintBounds;
558
    if (target is! RenderBox)
559
      return RevealedOffset(offset: offset.pixels, rect: rect);
560

561 562
    final RenderBox targetBox = target;
    final Matrix4 transform = targetBox.getTransformTo(this);
563
    final Rect bounds = MatrixUtils.transformRect(transform, rect);
564 565
    final Size contentSize = child.size;

566 567 568
    double leadingScrollOffset;
    double targetMainAxisExtent;
    double mainAxisExtent;
569 570 571 572

    assert(axisDirection != null);
    switch (axisDirection) {
      case AxisDirection.up:
573 574 575
        mainAxisExtent = size.height;
        leadingScrollOffset = contentSize.height - bounds.bottom;
        targetMainAxisExtent = bounds.height;
576 577
        break;
      case AxisDirection.right:
578 579 580
        mainAxisExtent = size.width;
        leadingScrollOffset = bounds.left;
        targetMainAxisExtent = bounds.width;
581 582
        break;
      case AxisDirection.down:
583 584 585
        mainAxisExtent = size.height;
        leadingScrollOffset = bounds.top;
        targetMainAxisExtent = bounds.height;
586 587
        break;
      case AxisDirection.left:
588 589 590
        mainAxisExtent = size.width;
        leadingScrollOffset = contentSize.width - bounds.right;
        targetMainAxisExtent = bounds.width;
591 592 593
        break;
    }

594 595
    final double targetOffset = leadingScrollOffset - (mainAxisExtent - targetMainAxisExtent) * alignment;
    final Rect targetRect = bounds.shift(_paintOffsetForPosition(targetOffset));
596
    return RevealedOffset(offset: targetOffset, rect: targetRect);
597
  }
598 599

  @override
600 601 602 603 604 605
  void showOnScreen({
    RenderObject descendant,
    Rect rect,
    Duration duration = Duration.zero,
    Curve curve = Curves.ease,
  }) {
606 607 608 609 610 611 612 613 614
    if (!offset.allowImplicitScrolling) {
      return super.showOnScreen(
        descendant: descendant,
        rect: rect,
        duration: duration,
        curve: curve,
      );
    }

615 616 617 618 619 620 621 622 623 624 625 626 627
    final Rect newRect = RenderViewportBase.showInViewport(
      descendant: descendant,
      viewport: this,
      offset: offset,
      rect: rect,
      duration: duration,
      curve: curve,
    );
    super.showOnScreen(
      rect: newRect,
      duration: duration,
      curve: curve,
    );
628
  }
629 630 631 632 633 634

  @override
  Rect describeSemanticsClip(RenderObject child) {
    assert(axis != null);
    switch (axis) {
      case Axis.vertical:
635
        return Rect.fromLTRB(
636 637 638 639 640 641
          semanticBounds.left,
          semanticBounds.top - cacheExtent,
          semanticBounds.right,
          semanticBounds.bottom + cacheExtent,
        );
      case Axis.horizontal:
642
        return Rect.fromLTRB(
643 644 645 646 647 648 649 650
          semanticBounds.left - cacheExtent,
          semanticBounds.top,
          semanticBounds.right + cacheExtent,
          semanticBounds.bottom,
        );
    }
    return null;
  }
651
}