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

5
import 'dart:async';
6
import 'dart:ui';
7

8
import 'package:flutter/gestures.dart';
9
import 'package:flutter/rendering.dart';
10
import 'package:flutter/scheduler.dart';
11 12 13 14

import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.dart';
15
import 'notification_listener.dart';
16
import 'scroll_configuration.dart';
17
import 'scroll_context.dart';
18
import 'scroll_controller.dart';
19
import 'scroll_physics.dart';
20
import 'scroll_position.dart';
21
import 'scroll_position_with_single_context.dart';
22
import 'ticker_provider.dart';
23 24 25 26
import 'viewport.dart';

export 'package:flutter/physics.dart' show Tolerance;

27 28
/// Signature used by [Scrollable] to build the viewport through which the
/// scrollable content is displayed.
29
typedef ViewportBuilder = Widget Function(BuildContext context, ViewportOffset position);
30

31 32 33 34 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
/// A widget that scrolls.
///
/// [Scrollable] implements the interaction model for a scrollable widget,
/// including gesture recognition, but does not have an opinion about how the
/// viewport, which actually displays the children, is constructed.
///
/// It's rare to construct a [Scrollable] directly. Instead, consider [ListView]
/// or [GridView], which combine scrolling, viewporting, and a layout model. To
/// combine layout models (or to use a custom layout mode), consider using
/// [CustomScrollView].
///
/// The static [Scrollable.of] and [Scrollable.ensureVisible] functions are
/// often used to interact with the [Scrollable] widget inside a [ListView] or
/// a [GridView].
///
/// To further customize scrolling behavior with a [Scrollable]:
///
/// 1. You can provide a [viewportBuilder] to customize the child model. For
///    example, [SingleChildScrollView] uses a viewport that displays a single
///    box child whereas [CustomScrollView] uses a [Viewport] or a
///    [ShrinkWrappingViewport], both of which display a list of slivers.
///
/// 2. You can provide a custom [ScrollController] that creates a custom
///    [ScrollPosition] subclass. For example, [PageView] uses a
///    [PageController], which creates a page-oriented scroll position subclass
///    that keeps the same page visible when the [Scrollable] resizes.
///
/// See also:
///
///  * [ListView], which is a commonly used [ScrollView] that displays a
///    scrolling, linear list of child widgets.
///  * [PageView], which is a scrolling list of child widgets that are each the
///    size of the viewport.
///  * [GridView], which is a [ScrollView] that displays a scrolling, 2D array
///    of child widgets.
///  * [CustomScrollView], which is a [ScrollView] that creates custom scroll
///    effects using slivers.
///  * [SingleChildScrollView], which is a scrollable widget that has a single
///    child.
70
///  * [ScrollNotification] and [NotificationListener], which can be used to watch
71
///    the scroll position without using a [ScrollController].
Adam Barth's avatar
Adam Barth committed
72
class Scrollable extends StatefulWidget {
73 74 75
  /// Creates a widget that scrolls.
  ///
  /// The [axisDirection] and [viewportBuilder] arguments must not be null.
76
  const Scrollable({
77
    Key key,
78
    this.axisDirection = AxisDirection.down,
79
    this.controller,
Adam Barth's avatar
Adam Barth committed
80
    this.physics,
81
    @required this.viewportBuilder,
82
    this.excludeFromSemantics = false,
83
    this.semanticChildCount,
84
    this.dragStartBehavior = DragStartBehavior.start,
85
  }) : assert(axisDirection != null),
86
       assert(dragStartBehavior != null),
87
       assert(viewportBuilder != null),
88
       assert(excludeFromSemantics != null),
89
       super (key: key);
90

91 92 93 94 95 96 97 98 99 100
  /// The direction in which this widget scrolls.
  ///
  /// For example, if the [axisDirection] is [AxisDirection.down], increasing
  /// the scroll position will cause content below the bottom of the viewport to
  /// become visible through the viewport. Similarly, if [axisDirection] is
  /// [AxisDirection.right], increasing the scroll position will cause content
  /// beyond the right edge of the viewport to become visible through the
  /// viewport.
  ///
  /// Defaults to [AxisDirection.down].
101 102
  final AxisDirection axisDirection;

103 104 105
  /// An object that can be used to control the position to which this widget is
  /// scrolled.
  ///
106 107 108 109 110 111 112 113
  /// 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]).
  ///
114 115 116 117
  /// See also:
  ///
  ///  * [ensureVisible], which animates the scroll position to reveal a given
  ///    [BuildContext].
118 119
  final ScrollController controller;

120 121 122 123 124
  /// How the widgets should respond to user input.
  ///
  /// For example, determines how the widget continues to animate after the
  /// user stops dragging the scroll view.
  ///
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  /// Defaults to matching platform conventions via the physics provided from
  /// the ambient [ScrollConfiguration].
  ///
  /// The physics can be changed dynamically, but new physics will only take
  /// effect if the _class_ of the provided object changes. Merely constructing
  /// a new instance with a different configuration is insufficient to cause the
  /// physics to be reapplied. (This is because the final object used is
  /// generated dynamically, which can be relatively expensive, and it would be
  /// inefficient to speculatively create this object each frame to see if the
  /// physics should be updated.)
  ///
  /// See also:
  ///
  ///  * [AlwaysScrollableScrollPhysics], which can be used to indicate that the
  ///    scrollable should react to scroll requests (and possible overscroll)
  ///    even if the scrollable's contents fit without scrolling being necessary.
Adam Barth's avatar
Adam Barth committed
141 142
  final ScrollPhysics physics;

143 144 145 146 147 148 149 150 151 152
  /// Builds the viewport through which the scrollable content is displayed.
  ///
  /// A typical viewport uses the given [ViewportOffset] to determine which part
  /// of its content is actually visible through the viewport.
  ///
  /// See also:
  ///
  ///  * [Viewport], which is a viewport that displays a list of slivers.
  ///  * [ShrinkWrappingViewport], which is a viewport that displays a list of
  ///    slivers and sizes itself based on the size of the slivers.
153
  final ViewportBuilder viewportBuilder;
154

155 156 157 158 159 160 161 162 163 164 165 166 167
  /// Whether the scroll actions introduced by this [Scrollable] are exposed
  /// in the semantics tree.
  ///
  /// Text fields with an overflow are usually scrollable to make sure that the
  /// user can get to the beginning/end of the entered text. However, these
  /// scrolling actions are generally not exposed to the semantics layer.
  ///
  /// See also:
  ///
  ///  * [GestureDetector.excludeFromSemantics], which is used to accomplish the
  ///    exclusion.
  final bool excludeFromSemantics;

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  /// The number of children that will contribute semantic information.
  ///
  /// The value will be null if the number of children is unknown or unbounded.
  ///
  /// Some subtypes of [ScrollView] can infer this value automatically. For
  /// example [ListView] will use the number of widgets in the child list,
  /// while the [new ListView.separated] constructor will use half that amount.
  ///
  /// For [CustomScrollView] and other types which do not receive a builder
  /// or list of widgets, the child count must be explicitly provided.
  ///
  /// See also:
  ///
  ///  * [CustomScrollView], for an explanation of scroll semantics.
  ///  * [SemanticsConfiguration.scrollChildCount], the corresponding semantics property.
  final int semanticChildCount;

185
  // TODO(jslavitz): Set the DragStartBehavior default to be start across all widgets.
186 187 188 189 190 191 192 193 194 195 196
  /// {@template flutter.widgets.scrollable.dragStartBehavior}
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], scrolling drag behavior will
  /// begin upon the detection of a drag gesture. If set to
  /// [DragStartBehavior.down] it will begin when a down event is first detected.
  ///
  /// In general, setting this to [DragStartBehavior.start] will make drag
  /// animation smoother and setting it to [DragStartBehavior.down] will make
  /// drag behavior feel slightly more reactive.
  ///
197
  /// By default, the drag start behavior is [DragStartBehavior.start].
198 199 200 201 202 203 204
  ///
  /// See also:
  ///
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

205 206 207
  /// The axis along which the scroll view scrolls.
  ///
  /// Determined by the [axisDirection].
208 209 210
  Axis get axis => axisDirectionToAxis(axisDirection);

  @override
211
  ScrollableState createState() => ScrollableState();
212 213

  @override
214 215
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
216 217
    properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
    properties.add(DiagnosticsProperty<ScrollPhysics>('physics', physics));
218
  }
219 220 221 222 223 224

  /// The state from the closest instance of this class that encloses the given context.
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
Adam Barth's avatar
Adam Barth committed
225
  /// ScrollableState scrollable = Scrollable.of(context);
226
  /// ```
Adam Barth's avatar
Adam Barth committed
227
  static ScrollableState of(BuildContext context) {
228 229
    final _ScrollableScope widget = context.inheritFromWidgetOfExactType(_ScrollableScope);
    return widget?.scrollable;
230 231
  }

232 233
  /// Scrolls the scrollables that enclose the given context so as to make the
  /// given context visible.
234 235
  static Future<void> ensureVisible(
    BuildContext context, {
236 237 238
    double alignment = 0.0,
    Duration duration = Duration.zero,
    Curve curve = Curves.ease,
239
  }) {
240
    final List<Future<void>> futures = <Future<void>>[];
241

Adam Barth's avatar
Adam Barth committed
242
    ScrollableState scrollable = Scrollable.of(context);
243
    while (scrollable != null) {
244 245 246 247 248 249
      futures.add(scrollable.position.ensureVisible(
        context.findRenderObject(),
        alignment: alignment,
        duration: duration,
        curve: curve,
      ));
250
      context = scrollable.context;
Adam Barth's avatar
Adam Barth committed
251
      scrollable = Scrollable.of(context);
252 253
    }

254
    if (futures.isEmpty || duration == Duration.zero)
255
      return Future<void>.value();
256
    if (futures.length == 1)
257
      return futures.single;
258
    return Future.wait<void>(futures).then<void>((List<void> _) => null);
259
  }
260 261
}

262 263 264
// Enable Scrollable.of() to work as if ScrollableState was an inherited widget.
// ScrollableState.build() always rebuilds its _ScrollableScope.
class _ScrollableScope extends InheritedWidget {
265
  const _ScrollableScope({
266 267 268 269
    Key key,
    @required this.scrollable,
    @required this.position,
    @required Widget child
270 271 272
  }) : assert(scrollable != null),
       assert(child != null),
       super(key: key, child: child);
273 274 275 276 277 278 279 280 281 282

  final ScrollableState scrollable;
  final ScrollPosition position;

  @override
  bool updateShouldNotify(_ScrollableScope old) {
    return position != old.position;
  }
}

Adam Barth's avatar
Adam Barth committed
283
/// State object for a [Scrollable] widget.
284
///
Adam Barth's avatar
Adam Barth committed
285
/// To manipulate a [Scrollable] widget's scroll position, use the object
286 287
/// obtained from the [position] property.
///
Adam Barth's avatar
Adam Barth committed
288 289
/// To be informed of when a [Scrollable] widget is scrolling, use a
/// [NotificationListener] to listen for [ScrollNotification] notifications.
290 291
///
/// This class is not intended to be subclassed. To specialize the behavior of a
Adam Barth's avatar
Adam Barth committed
292 293
/// [Scrollable], provide it with a [ScrollPhysics].
class ScrollableState extends State<Scrollable> with TickerProviderStateMixin
294 295
    implements ScrollContext {
  /// The manager for this [Scrollable] widget's viewport position.
296
  ///
Adam Barth's avatar
Adam Barth committed
297
  /// To control what kind of [ScrollPosition] is created for a [Scrollable],
298 299
  /// provide it with custom [ScrollController] that creates the appropriate
  /// [ScrollPosition] in its [ScrollController.createScrollPosition] method.
300 301 302
  ScrollPosition get position => _position;
  ScrollPosition _position;

303 304 305
  @override
  AxisDirection get axisDirection => widget.axisDirection;

Adam Barth's avatar
Adam Barth committed
306
  ScrollBehavior _configuration;
307
  ScrollPhysics _physics;
308

309
  // Only call this from places that will definitely trigger a rebuild.
310
  void _updatePosition() {
Adam Barth's avatar
Adam Barth committed
311
    _configuration = ScrollConfiguration.of(context);
312
    _physics = _configuration.getScrollPhysics(context);
313 314 315
    if (widget.physics != null)
      _physics = widget.physics.applyTo(_physics);
    final ScrollController controller = widget.controller;
316 317
    final ScrollPosition oldPosition = position;
    if (oldPosition != null) {
318
      controller?.detach(oldPosition);
319 320 321
      // It's important that we not dispose the old position until after the
      // viewport has had a chance to unregister its listeners from the old
      // position. So, schedule a microtask to do it.
322 323
      scheduleMicrotask(oldPosition.dispose);
    }
324

325
    _position = controller?.createScrollPosition(_physics, this, oldPosition)
326
      ?? ScrollPositionWithSingleContext(physics: _physics, context: this, oldPosition: oldPosition);
327
    assert(position != null);
328
    controller?.attach(position);
329 330 331
  }

  @override
332 333
  void didChangeDependencies() {
    super.didChangeDependencies();
334 335 336
    _updatePosition();
  }

337
  bool _shouldUpdatePosition(Scrollable oldWidget) {
338 339 340 341 342 343 344 345 346 347
    ScrollPhysics newPhysics = widget.physics;
    ScrollPhysics oldPhysics = oldWidget.physics;
    do {
      if (newPhysics?.runtimeType != oldPhysics?.runtimeType)
        return true;
      newPhysics = newPhysics?.parent;
      oldPhysics = oldPhysics?.parent;
    } while (newPhysics != null || oldPhysics != null);

    return widget.controller?.runtimeType != oldWidget.controller?.runtimeType;
348 349
  }

350
  @override
351 352
  void didUpdateWidget(Scrollable oldWidget) {
    super.didUpdateWidget(oldWidget);
353

354 355 356
    if (widget.controller != oldWidget.controller) {
      oldWidget.controller?.detach(position);
      widget.controller?.attach(position);
357 358
    }

359
    if (_shouldUpdatePosition(oldWidget))
360 361 362 363 364
      _updatePosition();
  }

  @override
  void dispose() {
365
    widget.controller?.detach(position);
366 367 368 369 370
    position.dispose();
    super.dispose();
  }


371 372
  // SEMANTICS

373
  final GlobalKey _scrollSemanticsKey = GlobalKey();
374 375 376 377 378 379 380 381 382

  @override
  @protected
  void setSemanticsActions(Set<SemanticsAction> actions) {
    if (_gestureDetectorKey.currentState != null)
      _gestureDetectorKey.currentState.replaceSemanticsActions(actions);
  }


383 384
  // GESTURE RECOGNITION AND POINTER IGNORING

385 386
  final GlobalKey<RawGestureDetectorState> _gestureDetectorKey = GlobalKey<RawGestureDetectorState>();
  final GlobalKey _ignorePointerKey = GlobalKey();
387 388 389 390 391 392 393 394

  // This field is set during layout, and then reused until the next time it is set.
  Map<Type, GestureRecognizerFactory> _gestureRecognizers = const <Type, GestureRecognizerFactory>{};
  bool _shouldIgnorePointer = false;

  bool _lastCanDrag;
  Axis _lastAxisDirection;

395 396 397
  @override
  @protected
  void setCanDrag(bool canDrag) {
398
    if (canDrag == _lastCanDrag && (!canDrag || widget.axis == _lastAxisDirection))
399 400 401 402
      return;
    if (!canDrag) {
      _gestureRecognizers = const <Type, GestureRecognizerFactory>{};
    } else {
403
      switch (widget.axis) {
404 405
        case Axis.vertical:
          _gestureRecognizers = <Type, GestureRecognizerFactory>{
406 407
            VerticalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>(
              () => VerticalDragGestureRecognizer(),
408 409 410 411 412 413 414 415 416
              (VerticalDragGestureRecognizer instance) {
                instance
                  ..onDown = _handleDragDown
                  ..onStart = _handleDragStart
                  ..onUpdate = _handleDragUpdate
                  ..onEnd = _handleDragEnd
                  ..onCancel = _handleDragCancel
                  ..minFlingDistance = _physics?.minFlingDistance
                  ..minFlingVelocity = _physics?.minFlingVelocity
417 418
                  ..maxFlingVelocity = _physics?.maxFlingVelocity
                  ..dragStartBehavior = widget.dragStartBehavior;
419 420
              },
            ),
421 422 423 424
          };
          break;
        case Axis.horizontal:
          _gestureRecognizers = <Type, GestureRecognizerFactory>{
425 426
            HorizontalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>(
              () => HorizontalDragGestureRecognizer(),
427 428 429 430 431 432 433 434 435
              (HorizontalDragGestureRecognizer instance) {
                instance
                  ..onDown = _handleDragDown
                  ..onStart = _handleDragStart
                  ..onUpdate = _handleDragUpdate
                  ..onEnd = _handleDragEnd
                  ..onCancel = _handleDragCancel
                  ..minFlingDistance = _physics?.minFlingDistance
                  ..minFlingVelocity = _physics?.minFlingVelocity
436 437
                  ..maxFlingVelocity = _physics?.maxFlingVelocity
                  ..dragStartBehavior = widget.dragStartBehavior;
438 439
              },
            ),
440 441 442 443 444
          };
          break;
      }
    }
    _lastCanDrag = canDrag;
445
    _lastAxisDirection = widget.axis;
446 447 448 449
    if (_gestureDetectorKey.currentState != null)
      _gestureDetectorKey.currentState.replaceGestureRecognizers(_gestureRecognizers);
  }

450 451 452 453 454 455
  @override
  TickerProvider get vsync => this;

  @override
  @protected
  void setIgnorePointer(bool value) {
456 457 458 459
    if (_shouldIgnorePointer == value)
      return;
    _shouldIgnorePointer = value;
    if (_ignorePointerKey.currentContext != null) {
460
      final RenderIgnorePointer renderBox = _ignorePointerKey.currentContext.findRenderObject();
461 462 463 464
      renderBox.ignoring = _shouldIgnorePointer;
    }
  }

465
  @override
466
  BuildContext get notificationContext => _gestureDetectorKey.currentContext;
467

468 469 470
  @override
  BuildContext get storageContext => context;

471 472
  // TOUCH HANDLERS

473
  Drag _drag;
474
  ScrollHoldController _hold;
475 476 477

  void _handleDragDown(DragDownDetails details) {
    assert(_drag == null);
478 479
    assert(_hold == null);
    _hold = position.hold(_disposeHold);
480 481 482
  }

  void _handleDragStart(DragStartDetails details) {
Ian Hickson's avatar
Ian Hickson committed
483 484 485
    // It's possible for _hold to become null between _handleDragDown and
    // _handleDragStart, for example if some user code calls jumpTo or otherwise
    // triggers a new activity to begin.
486
    assert(_drag == null);
487
    _drag = position.drag(details, _disposeDrag);
488
    assert(_drag != null);
489
    assert(_hold == null);
490 491 492
  }

  void _handleDragUpdate(DragUpdateDetails details) {
493
    // _drag might be null if the drag activity ended and called _disposeDrag.
494
    assert(_hold == null || _drag == null);
495
    _drag?.update(details);
496 497 498
  }

  void _handleDragEnd(DragEndDetails details) {
499
    // _drag might be null if the drag activity ended and called _disposeDrag.
500
    assert(_hold == null || _drag == null);
501
    _drag?.end(details);
502 503 504
    assert(_drag == null);
  }

505
  void _handleDragCancel() {
506
    // _hold might be null if the drag started.
507
    // _drag might be null if the drag activity ended and called _disposeDrag.
508 509
    assert(_hold == null || _drag == null);
    _hold?.cancel();
510
    _drag?.cancel();
511
    assert(_hold == null);
512 513 514
    assert(_drag == null);
  }

515 516 517 518
  void _disposeHold() {
    _hold = null;
  }

519
  void _disposeDrag() {
520 521 522
    _drag = null;
  }

523 524 525 526 527 528

  // DESCRIPTION

  @override
  Widget build(BuildContext context) {
    assert(position != null);
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    // _ScrollableScope must be placed above the BuildContext returned by notificationContext
    // so that we can get this ScrollableState by doing the following:
    //
    // ScrollNotification notification;
    // Scrollable.of(notification.context)
    //
    // Since notificationContext is pointing to _gestureDetectorKey.context, _ScrollableScope
    // must be placed above the widget using it: RawGestureDetector
    Widget result = _ScrollableScope(
      scrollable: this,
      position: position,
      // TODO(ianh): Having all these global keys is sad.
      child: RawGestureDetector(
        key: _gestureDetectorKey,
        gestures: _gestureRecognizers,
        behavior: HitTestBehavior.opaque,
        excludeFromSemantics: widget.excludeFromSemantics,
        child: Semantics(
          explicitChildNodes: !widget.excludeFromSemantics,
          child: IgnorePointer(
            key: _ignorePointerKey,
            ignoring: _shouldIgnorePointer,
            ignoringSemantics: false,
552
            child: widget.viewportBuilder(context, position),
553
          ),
554
        ),
555 556
      ),
    );
557 558

    if (!widget.excludeFromSemantics) {
559
      result = _ScrollSemantics(
Ian Hickson's avatar
Ian Hickson committed
560
        key: _scrollSemanticsKey,
561
        child: result,
562
        position: position,
563
        allowImplicitScrolling: widget?.physics?.allowImplicitScrolling ?? _physics.allowImplicitScrolling,
564
        semanticChildCount: widget.semanticChildCount,
565 566 567
      );
    }

568
    return _configuration.buildViewportChrome(context, result, widget.axisDirection);
569 570 571
  }

  @override
572 573
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
574
    properties.add(DiagnosticsProperty<ScrollPosition>('position', position));
575 576
  }
}
577

Ian Hickson's avatar
Ian Hickson committed
578
/// With [_ScrollSemantics] certain child [SemanticsNode]s can be
579 580 581 582 583 584 585 586 587 588 589 590 591
/// excluded from the scrollable area for semantics purposes.
///
/// Nodes, that are to be excluded, have to be tagged with
/// [RenderViewport.excludeFromScrolling] and the [RenderAbstractViewport] in
/// use has to add the [RenderViewport.useTwoPaneSemantics] tag to its
/// [SemanticsConfiguration] by overriding
/// [RenderObject.describeSemanticsConfiguration].
///
/// If the tag [RenderViewport.useTwoPaneSemantics] is present on the viewport,
/// two semantics nodes will be used to represent the [Scrollable]: The outer
/// node will contain all children, that are excluded from scrolling. The inner
/// node, which is annotated with the scrolling actions, will house the
/// scrollable children.
Ian Hickson's avatar
Ian Hickson committed
592 593
class _ScrollSemantics extends SingleChildRenderObjectWidget {
  const _ScrollSemantics({
594 595
    Key key,
    @required this.position,
596
    @required this.allowImplicitScrolling,
597
    @required this.semanticChildCount,
598
    Widget child
599 600
  }) : assert(position != null),
       super(key: key, child: child);
601 602

  final ScrollPosition position;
603
  final bool allowImplicitScrolling;
604
  final int semanticChildCount;
605 606

  @override
Ian Hickson's avatar
Ian Hickson committed
607
  _RenderScrollSemantics createRenderObject(BuildContext context) {
608
    return _RenderScrollSemantics(
609 610
      position: position,
      allowImplicitScrolling: allowImplicitScrolling,
611
      semanticChildCount: semanticChildCount,
612 613 614
    );
  }

615
  @override
Ian Hickson's avatar
Ian Hickson committed
616
  void updateRenderObject(BuildContext context, _RenderScrollSemantics renderObject) {
617 618
    renderObject
      ..allowImplicitScrolling = allowImplicitScrolling
619 620
      ..position = position
      ..semanticChildCount = semanticChildCount;
621
  }
622 623
}

Ian Hickson's avatar
Ian Hickson committed
624 625
class _RenderScrollSemantics extends RenderProxyBox {
  _RenderScrollSemantics({
626
    @required ScrollPosition position,
627
    @required bool allowImplicitScrolling,
628
    @required int semanticChildCount,
629
    RenderBox child,
630 631
  }) : _position = position,
       _allowImplicitScrolling = allowImplicitScrolling,
632
       _semanticChildCount = semanticChildCount,
633 634
       assert(position != null),
       super(child) {
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    position.addListener(markNeedsSemanticsUpdate);
  }

  /// Whether this render object is excluded from the semantic tree.
  ScrollPosition get position => _position;
  ScrollPosition _position;
  set position(ScrollPosition value) {
    assert(value != null);
    if (value == _position)
      return;
    _position.removeListener(markNeedsSemanticsUpdate);
    _position = value;
    _position.addListener(markNeedsSemanticsUpdate);
    markNeedsSemanticsUpdate();
  }
650

651 652 653 654 655 656 657 658 659 660
  /// Whether this node can be scrolled implicitly.
  bool get allowImplicitScrolling => _allowImplicitScrolling;
  bool _allowImplicitScrolling;
  set allowImplicitScrolling(bool value) {
    if (value == _allowImplicitScrolling)
      return;
    _allowImplicitScrolling = value;
    markNeedsSemanticsUpdate();
  }

661 662 663 664 665 666 667 668 669
  int get semanticChildCount => _semanticChildCount;
  int _semanticChildCount;
  set semanticChildCount(int value) {
    if (value == semanticChildCount)
      return;
    _semanticChildCount = value;
    markNeedsSemanticsUpdate();
  }

670 671 672 673
  @override
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isSemanticBoundary = true;
674 675
    if (position.haveDimensions) {
      config
676
          ..hasImplicitScrolling = allowImplicitScrolling
677 678
          ..scrollPosition = _position.pixels
          ..scrollExtentMax = _position.maxScrollExtent
679 680
          ..scrollExtentMin = _position.minScrollExtent
          ..scrollChildCount = semanticChildCount;
681
    }
682 683 684 685 686 687 688 689 690 691 692
  }

  SemanticsNode _innerNode;

  @override
  void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children) {
    if (children.isEmpty || !children.first.isTagged(RenderViewport.useTwoPaneSemantics)) {
      super.assembleSemanticsNode(node, config, children);
      return;
    }

693
    _innerNode ??= SemanticsNode(showOnScreen: showOnScreen);
694 695 696 697
    _innerNode
      ..isMergedIntoParent = node.isPartOfNodeMerging
      ..rect = Offset.zero & node.rect.size;

698
    int firstVisibleIndex;
699 700 701 702 703 704
    final List<SemanticsNode> excluded = <SemanticsNode>[_innerNode];
    final List<SemanticsNode> included = <SemanticsNode>[];
    for (SemanticsNode child in children) {
      assert(child.isTagged(RenderViewport.useTwoPaneSemantics));
      if (child.isTagged(RenderViewport.excludeFromScrolling))
        excluded.add(child);
705 706 707
      else {
        if (!child.hasFlag(SemanticsFlag.isHidden))
          firstVisibleIndex ??= child.indexInParent;
708
        included.add(child);
709
      }
710
    }
711
    config.scrollIndex = firstVisibleIndex;
712 713 714 715
    node.updateWith(config: null, childrenInInversePaintOrder: excluded);
    _innerNode.updateWith(config: config, childrenInInversePaintOrder: included);
  }

716 717 718 719
  @override
  void clearSemantics() {
    super.clearSemantics();
    _innerNode = null;
720 721
  }
}