flexible_space_bar.dart 7.54 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 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;

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

import 'constants.dart';
import 'theme.dart';

13 14 15 16 17 18 19 20 21 22 23 24
/// The collapsing effect while the space bar expands or collapses.
enum CollapseMode {
  /// The background widget will scroll in a parallax fashion.
  parallax,

  /// The background widget pin in place until it reaches the min extent.
  pin,

  /// The background widget will act as normal with no collapsing effect.
  none,
}

25 26
/// The part of a material design [AppBar] that expands and collapses.
///
27 28 29 30
/// Most commonly used in in the [SliverAppBar.flexibleSpace] field, a flexible
/// space bar expands and contracts as the app scrolls so that the [AppBar]
/// reaches from the top of the app to the top of the scrolling contents of the
/// app.
31
///
32 33 34
/// The widget that sizes the [AppBar] must wrap it in the widget returned by
/// [FlexibleSpaceBar.createSettings], to convey sizing information down to the
/// [FlexibleSpaceBar].
35 36
///
/// See also:
Ian Hickson's avatar
Ian Hickson committed
37
///
38 39
///  * [SliverAppBar], which implements the expanding and contracting.
///  * [AppBar], which is used by [SliverAppBar].
40
///  * <https://material.google.com/patterns/scrolling-techniques.html>
41
class FlexibleSpaceBar extends StatefulWidget {
42 43
  /// Creates a flexible space bar.
  ///
44
  /// Most commonly used in the [AppBar.flexibleSpace] field.
45
  const FlexibleSpaceBar({
46 47 48
    Key key,
    this.title,
    this.background,
49 50 51 52
    this.centerTitle,
    this.collapseMode = CollapseMode.parallax
  }) : assert(collapseMode != null),
       super(key: key);
53

54 55 56
  /// The primary contents of the flexible space bar when expanded.
  ///
  /// Typically a [Text] widget.
57
  final Widget title;
58 59 60

  /// Shown behind the [title] when expanded.
  ///
61
  /// Typically an [Image] widget with [Image.fit] set to [BoxFit.cover].
62
  final Widget background;
63

64 65 66 67 68
  /// Whether the title should be centered.
  ///
  /// Defaults to being adapted to the current [TargetPlatform].
  final bool centerTitle;

69 70 71 72 73
  /// Collapse effect while scrolling.
  ///
  /// Defaults to [CollapseMode.parallax].
  final CollapseMode collapseMode;

74 75 76 77
  /// Wraps a widget that contains an [AppBar] to convey sizing information down
  /// to the [FlexibleSpaceBar].
  ///
  /// Used by [Scaffold] and [SliverAppBar].
78 79 80 81 82 83 84 85
  static Widget createSettings({
    double toolbarOpacity,
    double minExtent,
    double maxExtent,
    @required double currentExtent,
    @required Widget child,
  }) {
    assert(currentExtent != null);
86
    return _FlexibleSpaceBarSettings(
87 88 89 90 91 92 93 94
      toolbarOpacity: toolbarOpacity ?? 1.0,
      minExtent: minExtent ?? currentExtent,
      maxExtent: maxExtent ?? currentExtent,
      currentExtent: currentExtent,
      child: child,
    );
  }

95
  @override
96
  _FlexibleSpaceBarState createState() => _FlexibleSpaceBarState();
97 98 99
}

class _FlexibleSpaceBarState extends State<FlexibleSpaceBar> {
100
  bool _getEffectiveCenterTitle(ThemeData theme) {
101 102
    if (widget.centerTitle != null)
      return widget.centerTitle;
103 104 105
    assert(theme.platform != null);
    switch (theme.platform) {
      case TargetPlatform.android:
106
      case TargetPlatform.fuchsia:
107 108 109 110
        return false;
      case TargetPlatform.iOS:
        return true;
    }
111
    return null;
112 113
  }

114
  Alignment _getTitleAlignment(bool effectiveCenterTitle) {
115
    if (effectiveCenterTitle)
116
      return Alignment.bottomCenter;
117 118 119 120
    final TextDirection textDirection = Directionality.of(context);
    assert(textDirection != null);
    switch (textDirection) {
      case TextDirection.rtl:
121
        return Alignment.bottomRight;
122
      case TextDirection.ltr:
123
        return Alignment.bottomLeft;
124 125 126 127
    }
    return null;
  }

128 129 130 131 132 133 134 135
  double _getCollapsePadding(double t, _FlexibleSpaceBarSettings settings) {
    switch (widget.collapseMode) {
      case CollapseMode.pin:
        return -(settings.maxExtent - settings.currentExtent);
      case CollapseMode.none:
        return 0.0;
      case CollapseMode.parallax:
        final double deltaExtent = settings.maxExtent - settings.minExtent;
136
        return -Tween<double>(begin: 0.0, end: deltaExtent / 4.0).transform(t);
137 138 139 140
    }
    return null;
  }

141 142
  @override
  Widget build(BuildContext context) {
143
    final _FlexibleSpaceBarSettings settings = context.inheritFromWidgetOfExactType(_FlexibleSpaceBarSettings);
144 145 146
    assert(settings != null, 'A FlexibleSpaceBar must be wrapped in the widget returned by FlexibleSpaceBar.createSettings().');

    final List<Widget> children = <Widget>[];
147

148
    final double deltaExtent = settings.maxExtent - settings.minExtent;
149 150 151

    // 0.0 -> Expanded
    // 1.0 -> Collapsed to toolbar
152
    final double t = (1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent).clamp(0.0, 1.0);
153 154

    // background image
155
    if (widget.background != null) {
156
      final double fadeStart = math.max(0.0, 1.0 - kToolbarHeight / deltaExtent);
157
      const double fadeEnd = 1.0;
158
      assert(fadeStart <= fadeEnd);
159
      final double opacity = 1.0 - Interval(fadeStart, fadeEnd).transform(t);
160
      if (opacity > 0.0) {
161
        children.add(Positioned(
162
          top: _getCollapsePadding(t, settings),
163 164
          left: 0.0,
          right: 0.0,
165
          height: settings.maxExtent,
166
          child: Opacity(
167
            opacity: opacity,
168
            child: widget.background
169
          )
170 171
        ));
      }
172 173
    }

174
    if (widget.title != null) {
175 176 177 178 179 180 181
      Widget title;
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
          title = widget.title;
          break;
        case TargetPlatform.fuchsia:
        case TargetPlatform.android:
182
          title = Semantics(
183 184 185 186 187
            namesRoute: true,
            child: widget.title,
          );
      }

188
      final ThemeData theme = Theme.of(context);
189
      final double opacity = settings.toolbarOpacity;
190
      if (opacity > 0.0) {
191
        TextStyle titleStyle = theme.primaryTextTheme.title;
192
        titleStyle = titleStyle.copyWith(
193
          color: titleStyle.color.withOpacity(opacity)
194
        );
195
        final bool effectiveCenterTitle = _getEffectiveCenterTitle(theme);
196
        final double scaleValue = Tween<double>(begin: 1.5, end: 1.0).transform(t);
197
        final Matrix4 scaleTransform = Matrix4.identity()
198
          ..scale(scaleValue, scaleValue, 1.0);
199
        final Alignment titleAlignment = _getTitleAlignment(effectiveCenterTitle);
200 201
        children.add(Container(
          padding: EdgeInsetsDirectional.only(
202
            start: effectiveCenterTitle ? 0.0 : 72.0,
203 204
            bottom: 16.0
          ),
205
          child: Transform(
206
            alignment: titleAlignment,
207
            transform: scaleTransform,
208
            child: Align(
209
              alignment: titleAlignment,
210
              child: DefaultTextStyle(
211 212 213
                style: titleStyle,
                child: title,
              )
214 215
            )
          )
216 217
        ));
      }
218 219
    }

220
    return ClipRect(child: Stack(children: children));
221
  }
222 223 224
}

class _FlexibleSpaceBarSettings extends InheritedWidget {
225
  const _FlexibleSpaceBarSettings({
226 227 228 229 230 231 232 233 234 235 236 237
    Key key,
    this.toolbarOpacity,
    this.minExtent,
    this.maxExtent,
    this.currentExtent,
    Widget child,
  }) : super(key: key, child: child);

  final double toolbarOpacity;
  final double minExtent;
  final double maxExtent;
  final double currentExtent;
238 239

  @override
240 241 242 243 244
  bool updateShouldNotify(_FlexibleSpaceBarSettings oldWidget) {
    return toolbarOpacity != oldWidget.toolbarOpacity
        || minExtent != oldWidget.minExtent
        || maxExtent != oldWidget.maxExtent
        || currentExtent != oldWidget.currentExtent;
245
  }
246
}