flexible_space_bar.dart 8.97 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 86 87 88 89 90
  ///
  /// `toolbarOpacity` affects how transparent the text within the toolbar
  /// appears. `minExtent` sets the minimum height of the resulting
  /// [FlexibleSpaceBar] when fully collapsed. `maxExtent` sets the maximum
  /// height of the resulting [FlexibleSpaceBar] when fully expanded.
  /// `currentExtent` sets the scale of the [FlexibleSpaceBar.background] and
  /// [FlexibleSpaceBar.title] widgets of [FlexibleSpaceBar] upon
  /// initialization.
  ///
  /// See also:
  ///
  ///   * [FlexibleSpaceBarSettings] which creates a settings object that can be
  ///     used to specify these settings to a [FlexibleSpaceBar].
91 92 93 94 95 96 97 98
  static Widget createSettings({
    double toolbarOpacity,
    double minExtent,
    double maxExtent,
    @required double currentExtent,
    @required Widget child,
  }) {
    assert(currentExtent != null);
99
    return FlexibleSpaceBarSettings(
100 101 102 103 104 105 106 107
      toolbarOpacity: toolbarOpacity ?? 1.0,
      minExtent: minExtent ?? currentExtent,
      maxExtent: maxExtent ?? currentExtent,
      currentExtent: currentExtent,
      child: child,
    );
  }

108
  @override
109
  _FlexibleSpaceBarState createState() => _FlexibleSpaceBarState();
110 111 112
}

class _FlexibleSpaceBarState extends State<FlexibleSpaceBar> {
113
  bool _getEffectiveCenterTitle(ThemeData theme) {
114 115
    if (widget.centerTitle != null)
      return widget.centerTitle;
116 117 118
    assert(theme.platform != null);
    switch (theme.platform) {
      case TargetPlatform.android:
119
      case TargetPlatform.fuchsia:
120 121 122 123
        return false;
      case TargetPlatform.iOS:
        return true;
    }
124
    return null;
125 126
  }

127
  Alignment _getTitleAlignment(bool effectiveCenterTitle) {
128
    if (effectiveCenterTitle)
129
      return Alignment.bottomCenter;
130 131 132 133
    final TextDirection textDirection = Directionality.of(context);
    assert(textDirection != null);
    switch (textDirection) {
      case TextDirection.rtl:
134
        return Alignment.bottomRight;
135
      case TextDirection.ltr:
136
        return Alignment.bottomLeft;
137 138 139 140
    }
    return null;
  }

141
  double _getCollapsePadding(double t, FlexibleSpaceBarSettings settings) {
142 143 144 145 146 147 148
    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;
149
        return -Tween<double>(begin: 0.0, end: deltaExtent / 4.0).transform(t);
150 151 152 153
    }
    return null;
  }

154 155
  @override
  Widget build(BuildContext context) {
156
    final FlexibleSpaceBarSettings settings = context.inheritFromWidgetOfExactType(FlexibleSpaceBarSettings);
157 158 159
    assert(settings != null, 'A FlexibleSpaceBar must be wrapped in the widget returned by FlexibleSpaceBar.createSettings().');

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

161
    final double deltaExtent = settings.maxExtent - settings.minExtent;
162 163 164

    // 0.0 -> Expanded
    // 1.0 -> Collapsed to toolbar
165
    final double t = (1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent).clamp(0.0, 1.0);
166 167

    // background image
168
    if (widget.background != null) {
169
      final double fadeStart = math.max(0.0, 1.0 - kToolbarHeight / deltaExtent);
170
      const double fadeEnd = 1.0;
171
      assert(fadeStart <= fadeEnd);
172
      final double opacity = 1.0 - Interval(fadeStart, fadeEnd).transform(t);
173
      if (opacity > 0.0) {
174
        children.add(Positioned(
175
          top: _getCollapsePadding(t, settings),
176 177
          left: 0.0,
          right: 0.0,
178
          height: settings.maxExtent,
179
          child: Opacity(
180
            opacity: opacity,
181
            child: widget.background
182
          )
183 184
        ));
      }
185 186
    }

187
    if (widget.title != null) {
188 189 190 191 192 193 194
      Widget title;
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
          title = widget.title;
          break;
        case TargetPlatform.fuchsia:
        case TargetPlatform.android:
195
          title = Semantics(
196 197 198 199 200
            namesRoute: true,
            child: widget.title,
          );
      }

201
      final ThemeData theme = Theme.of(context);
202
      final double opacity = settings.toolbarOpacity;
203
      if (opacity > 0.0) {
204
        TextStyle titleStyle = theme.primaryTextTheme.title;
205
        titleStyle = titleStyle.copyWith(
206
          color: titleStyle.color.withOpacity(opacity)
207
        );
208
        final bool effectiveCenterTitle = _getEffectiveCenterTitle(theme);
209
        final double scaleValue = Tween<double>(begin: 1.5, end: 1.0).transform(t);
210
        final Matrix4 scaleTransform = Matrix4.identity()
211
          ..scale(scaleValue, scaleValue, 1.0);
212
        final Alignment titleAlignment = _getTitleAlignment(effectiveCenterTitle);
213 214
        children.add(Container(
          padding: EdgeInsetsDirectional.only(
215
            start: effectiveCenterTitle ? 0.0 : 72.0,
216 217
            bottom: 16.0
          ),
218
          child: Transform(
219
            alignment: titleAlignment,
220
            transform: scaleTransform,
221
            child: Align(
222
              alignment: titleAlignment,
223
              child: DefaultTextStyle(
224 225 226
                style: titleStyle,
                child: title,
              )
227 228
            )
          )
229 230
        ));
      }
231 232
    }

233
    return ClipRect(child: Stack(children: children));
234
  }
235 236
}

237 238 239 240 241 242 243 244 245 246 247
/// Provides sizing and opacity information to a [FlexibleSpaceBar].
///
/// See also:
///
///   * [FlexibleSpaceBar] which creates a flexible space bar.
class FlexibleSpaceBarSettings extends InheritedWidget {
  /// Creates a Flexible Space Bar Settings widget.
  ///
  /// Used by [Scaffold] and [SliverAppBar]. [child] must have a
  /// [FlexibleSpaceBar] widget in its tree for the settings to take affect.
  const FlexibleSpaceBarSettings({
248 249 250 251
    Key key,
    this.toolbarOpacity,
    this.minExtent,
    this.maxExtent,
252 253 254 255
    @required this.currentExtent,
    @required Widget child,
  }) :  assert(currentExtent != null),
        super(key: key, child: child);
256

257
  /// Affects how transparent the text within the toolbar appears.
258
  final double toolbarOpacity;
259 260

  /// Minimum height of the resulting [FlexibleSpaceBar] when fully collapsed.
261
  final double minExtent;
262 263

  /// Maximum height of the resulting [FlexibleSpaceBar] when fully expanded.
264
  final double maxExtent;
265 266 267 268

  /// If the [FlexibleSpaceBar.title] or the [FlexibleSpaceBar.background] is
  /// not null, then this value is used to calculate the relative scale of
  /// these elements upon initialization.
269
  final double currentExtent;
270 271

  @override
272
  bool updateShouldNotify(FlexibleSpaceBarSettings oldWidget) {
273 274 275 276
    return toolbarOpacity != oldWidget.toolbarOpacity
        || minExtent != oldWidget.minExtent
        || maxExtent != oldWidget.maxExtent
        || currentExtent != oldWidget.currentExtent;
277
  }
278
}