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

5 6
// @dart = 2.8

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

import 'framework.dart';
import 'scroll_controller.dart';

12 13 14 15 16 17 18 19 20
/// Associates a [ScrollController] with a subtree.
///
/// When a [ScrollView] has [ScrollView.primary] set to true and is not given
/// an explicit [ScrollController], the [ScrollView] uses [of] to find the
/// [ScrollController] associated with its subtree.
///
/// This mechanism can be used to provide default behavior for scroll views in a
/// subtree. For example, the [Scaffold] uses this mechanism to implement the
/// scroll-to-top gesture on iOS.
21
class PrimaryScrollController extends InheritedWidget {
22
  /// Creates a widget that associates a [ScrollController] with a subtree.
23
  const PrimaryScrollController({
24 25
    Key key,
    @required this.controller,
26
    @required Widget child,
27 28
  }) : assert(controller != null),
       super(key: key, child: child);
29

30
  /// Creates a subtree without an associated [ScrollController].
31 32
  const PrimaryScrollController.none({
    Key key,
33
    @required Widget child,
34 35 36
  }) : controller = null,
       super(key: key, child: child);

37
  /// The [ScrollController] associated with the subtree.
38 39 40 41 42
  ///
  /// See also:
  ///
  ///  * [ScrollView.controller], which discusses the purpose of specifying a
  ///    scroll controller.
43 44
  final ScrollController controller;

45 46 47 48 49
  /// Returns the [ScrollController] most closely associated with the given
  /// context.
  ///
  /// Returns null if there is no [ScrollController] associated with the given
  /// context.
50
  static ScrollController of(BuildContext context) {
51
    final PrimaryScrollController result = context.dependOnInheritedWidgetOfExactType<PrimaryScrollController>();
52 53 54 55
    return result?.controller;
  }

  @override
56
  bool updateShouldNotify(PrimaryScrollController oldWidget) => controller != oldWidget.controller;
57 58

  @override
59 60
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
61
    properties.add(DiagnosticsProperty<ScrollController>('controller', controller, ifNull: 'no controller', showName: false));
62 63
  }
}