flexible_space_bar.dart 15 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// 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;
6
import 'dart:ui' as ui;
7 8 9

import 'package:flutter/widgets.dart';

10
import 'colors.dart';
11 12 13
import 'constants.dart';
import 'theme.dart';

14
/// The collapsing effect while the space bar collapses from its full size.
15 16 17 18 19 20 21 22 23 24 25
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,
}

26 27 28 29 30 31 32 33 34 35 36 37 38 39
/// The stretching effect while the space bar stretches beyond its full size.
enum StretchMode {
  /// The background widget will expand to fill the extra space.
  zoomBackground,

  /// The background will blur using a [ImageFilter.blur] effect.
  blurBackground,

  /// The title will fade away as the user over-scrolls.
  fadeTitle,
}

/// The part of a material design [AppBar] that expands, collapses, and
/// stretches.
40
///
41 42
/// {@youtube 560 315 https://www.youtube.com/watch?v=mSc7qFzxHDw}
///
43
/// Most commonly used in the [SliverAppBar.flexibleSpace] field, a flexible
44 45
/// 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
46 47 48 49
/// app. When using [SliverAppBar.flexibleSpace], the [SliverAppBar.expandedHeight]
/// must be large enough to accommodate the [SliverAppBar.flexibleSpace] widget.
///
/// Furthermore is included functionality for stretch behavior. When
50 51
/// [SliverAppBar.stretch] is true, and your [ScrollPhysics] allow for
/// overscroll, this space will stretch with the overscroll.
52
///
53 54 55
/// The widget that sizes the [AppBar] must wrap it in the widget returned by
/// [FlexibleSpaceBar.createSettings], to convey sizing information down to the
/// [FlexibleSpaceBar].
56
///
57
/// {@tool dartpad}
58 59 60 61 62 63 64
/// This sample application demonstrates the different features of the
/// [FlexibleSpaceBar] when used in a [SliverAppBar]. This app bar is configured
/// to stretch into the overscroll space, and uses the
/// [FlexibleSpaceBar.stretchModes] to apply `fadeTitle`, `blurBackground` and
/// `zoomBackground`. The app bar also makes use of [CollapseMode.parallax] by
/// default.
///
65
/// ** See code in examples/api/lib/material/flexible_space_bar/flexible_space_bar.0.dart **
66 67
/// {@end-tool}
///
68
/// See also:
Ian Hickson's avatar
Ian Hickson committed
69
///
70 71
///  * [SliverAppBar], which implements the expanding and contracting.
///  * [AppBar], which is used by [SliverAppBar].
72
///  * <https://material.io/design/components/app-bars-top.html#behavior>
73
class FlexibleSpaceBar extends StatefulWidget {
74 75
  /// Creates a flexible space bar.
  ///
76
  /// Most commonly used in the [AppBar.flexibleSpace] field.
77
  const FlexibleSpaceBar({
78
    Key? key,
79 80
    this.title,
    this.background,
81
    this.centerTitle,
82
    this.titlePadding,
83
    this.collapseMode = CollapseMode.parallax,
84
    this.stretchModes = const <StretchMode>[StretchMode.zoomBackground],
85 86
  }) : assert(collapseMode != null),
       super(key: key);
87

88 89 90
  /// The primary contents of the flexible space bar when expanded.
  ///
  /// Typically a [Text] widget.
91
  final Widget? title;
92 93 94

  /// Shown behind the [title] when expanded.
  ///
95
  /// Typically an [Image] widget with [Image.fit] set to [BoxFit.cover].
96
  final Widget? background;
97

98 99
  /// Whether the title should be centered.
  ///
100
  /// By default this property is true if the current target platform
101
  /// is [TargetPlatform.iOS] or [TargetPlatform.macOS], false otherwise.
102
  final bool? centerTitle;
103

104 105 106 107 108
  /// Collapse effect while scrolling.
  ///
  /// Defaults to [CollapseMode.parallax].
  final CollapseMode collapseMode;

109
  /// Stretch effect while over-scrolling.
110 111 112 113
  ///
  /// Defaults to include [StretchMode.zoomBackground].
  final List<StretchMode> stretchModes;

114 115 116 117 118 119 120 121 122
  /// Defines how far the [title] is inset from either the widget's
  /// bottom-left or its center.
  ///
  /// Typically this property is used to adjust how far the title is
  /// is inset from the bottom-left and it is specified along with
  /// [centerTitle] false.
  ///
  /// By default the value of this property is
  /// `EdgeInsetsDirectional.only(start: 72, bottom: 16)` if the title is
123
  /// not centered, `EdgeInsetsDirectional.only(start: 0, bottom: 16)` otherwise.
124
  final EdgeInsetsGeometry? titlePadding;
125

126 127 128 129
  /// Wraps a widget that contains an [AppBar] to convey sizing information down
  /// to the [FlexibleSpaceBar].
  ///
  /// Used by [Scaffold] and [SliverAppBar].
130 131 132 133 134 135 136
  ///
  /// `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
137
  /// initialization. `scrolledUnder` is true if the [FlexibleSpaceBar]
138 139
  /// overlaps the app's primary scrollable, false if it does not, and null
  /// if the caller has not determined as much.
140 141
  /// See also:
  ///
142 143
  ///  * [FlexibleSpaceBarSettings] which creates a settings object that can be
  ///    used to specify these settings to a [FlexibleSpaceBar].
144
  static Widget createSettings({
145 146 147
    double? toolbarOpacity,
    double? minExtent,
    double? maxExtent,
148
    bool? isScrolledUnder,
149 150
    required double currentExtent,
    required Widget child,
151 152
  }) {
    assert(currentExtent != null);
153
    return FlexibleSpaceBarSettings(
154 155 156
      toolbarOpacity: toolbarOpacity ?? 1.0,
      minExtent: minExtent ?? currentExtent,
      maxExtent: maxExtent ?? currentExtent,
157
      isScrolledUnder: isScrolledUnder,
158 159 160 161 162
      currentExtent: currentExtent,
      child: child,
    );
  }

163
  @override
164
  State<FlexibleSpaceBar> createState() => _FlexibleSpaceBarState();
165 166 167
}

class _FlexibleSpaceBarState extends State<FlexibleSpaceBar> {
168
  bool _getEffectiveCenterTitle(ThemeData theme) {
169
    if (widget.centerTitle != null)
170
      return widget.centerTitle!;
171 172 173
    assert(theme.platform != null);
    switch (theme.platform) {
      case TargetPlatform.android:
174
      case TargetPlatform.fuchsia:
175 176
      case TargetPlatform.linux:
      case TargetPlatform.windows:
177 178
        return false;
      case TargetPlatform.iOS:
179
      case TargetPlatform.macOS:
180 181 182 183
        return true;
    }
  }

184
  Alignment _getTitleAlignment(bool effectiveCenterTitle) {
185
    if (effectiveCenterTitle)
186
      return Alignment.bottomCenter;
187
    final TextDirection textDirection = Directionality.of(context);
188 189 190
    assert(textDirection != null);
    switch (textDirection) {
      case TextDirection.rtl:
191
        return Alignment.bottomRight;
192
      case TextDirection.ltr:
193
        return Alignment.bottomLeft;
194 195 196
    }
  }

197
  double _getCollapsePadding(double t, FlexibleSpaceBarSettings settings) {
198 199 200 201 202 203 204
    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;
205
        return -Tween<double>(begin: 0.0, end: deltaExtent / 4.0).transform(t);
206 207 208
    }
  }

209 210
  @override
  Widget build(BuildContext context) {
211 212
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
213
        final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>()!;
214 215 216 217
        assert(
          settings != null,
          'A FlexibleSpaceBar must be wrapped in the widget returned by FlexibleSpaceBar.createSettings().',
        );
218

219
        final List<Widget> children = <Widget>[];
220

221 222 223 224
        final double deltaExtent = settings.maxExtent - settings.minExtent;

        // 0.0 -> Expanded
        // 1.0 -> Collapsed to toolbar
225
        final double t = (1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent).clamp(0.0, 1.0);
226 227 228 229 230 231

        // background
        if (widget.background != null) {
          final double fadeStart = math.max(0.0, 1.0 - kToolbarHeight / deltaExtent);
          const double fadeEnd = 1.0;
          assert(fadeStart <= fadeEnd);
232 233 234 235 236
          // If the min and max extent are the same, the app bar cannot collapse
          // and the content should be visible, so opacity = 1.
          final double opacity = settings.maxExtent == settings.minExtent
              ? 1.0
              : 1.0 - Interval(fadeStart, fadeEnd).transform(t);
237
          double height = settings.maxExtent;
238

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
          // StretchMode.zoomBackground
          if (widget.stretchModes.contains(StretchMode.zoomBackground) &&
            constraints.maxHeight > height) {
            height = constraints.maxHeight;
          }
          children.add(Positioned(
            top: _getCollapsePadding(t, settings),
            left: 0.0,
            right: 0.0,
            height: height,
            child: Opacity(
              // IOS is relying on this semantics node to correctly traverse
              // through the app bar when it is collapsed.
              alwaysIncludeSemantics: true,
              opacity: opacity,
              child: widget.background,
            ),
          ));

          // StretchMode.blurBackground
          if (widget.stretchModes.contains(StretchMode.blurBackground) &&
            constraints.maxHeight > settings.maxExtent) {
            final double blurAmount = (constraints.maxHeight - settings.maxExtent) / 10;
            children.add(Positioned.fill(
              child: BackdropFilter(
                filter: ui.ImageFilter.blur(
                  sigmaX: blurAmount,
                  sigmaY: blurAmount,
267
                ),
268 269 270
                child: Container(
                  color: Colors.transparent,
                ),
271
              ),
272
            ));
273 274
          }
        }
275

276 277
        // title
        if (widget.title != null) {
278
          final ThemeData theme = Theme.of(context);
279

280
          Widget? title;
281 282
          switch (theme.platform) {
            case TargetPlatform.iOS:
283
            case TargetPlatform.macOS:
284 285 286
              title = widget.title;
              break;
            case TargetPlatform.android:
287 288 289
            case TargetPlatform.fuchsia:
            case TargetPlatform.linux:
            case TargetPlatform.windows:
290 291 292 293
              title = Semantics(
                namesRoute: true,
                child: widget.title,
              );
294
              break;
295 296 297 298 299 300
          }

          // StretchMode.fadeTitle
          if (widget.stretchModes.contains(StretchMode.fadeTitle) &&
            constraints.maxHeight > settings.maxExtent) {
            final double stretchOpacity = 1 -
301
              (((constraints.maxHeight - settings.maxExtent) / 100).clamp(0.0, 1.0));
302 303 304 305 306 307 308 309
            title = Opacity(
              opacity: stretchOpacity,
              child: title,
            );
          }

          final double opacity = settings.toolbarOpacity;
          if (opacity > 0.0) {
310
            TextStyle titleStyle = theme.primaryTextTheme.headline6!;
311
            titleStyle = titleStyle.copyWith(
312
              color: titleStyle.color!.withOpacity(opacity),
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            );
            final bool effectiveCenterTitle = _getEffectiveCenterTitle(theme);
            final EdgeInsetsGeometry padding = widget.titlePadding ??
              EdgeInsetsDirectional.only(
                start: effectiveCenterTitle ? 0.0 : 72.0,
                bottom: 16.0,
              );
            final double scaleValue = Tween<double>(begin: 1.5, end: 1.0).transform(t);
            final Matrix4 scaleTransform = Matrix4.identity()
              ..scale(scaleValue, scaleValue, 1.0);
            final Alignment titleAlignment = _getTitleAlignment(effectiveCenterTitle);
            children.add(Container(
              padding: padding,
              child: Transform(
                alignment: titleAlignment,
                transform: scaleTransform,
                child: Align(
                  alignment: titleAlignment,
                  child: DefaultTextStyle(
                    style: titleStyle,
333 334 335 336 337 338 339
                    child: LayoutBuilder(
                      builder: (BuildContext context, BoxConstraints constraints) {
                        return Container(
                          width: constraints.maxWidth / scaleValue,
                          alignment: titleAlignment,
                          child: title,
                        );
340
                      },
341
                    ),
342 343 344 345 346 347 348 349
                  ),
                ),
              ),
            ));
          }
        }

        return ClipRect(child: Stack(children: children));
350
      },
351
    );
352
  }
353 354
}

355 356 357 358
/// Provides sizing and opacity information to a [FlexibleSpaceBar].
///
/// See also:
///
359
///  * [FlexibleSpaceBar] which creates a flexible space bar.
360 361 362 363 364
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.
365 366 367
  ///
  /// The required [toolbarOpacity], [minExtent], [maxExtent], [currentExtent],
  /// and [child] parameters must not be null.
368
  const FlexibleSpaceBarSettings({
369 370 371 372 373 374
    Key? key,
    required this.toolbarOpacity,
    required this.minExtent,
    required this.maxExtent,
    required this.currentExtent,
    required Widget child,
375
    this.isScrolledUnder,
376 377 378 379 380 381 382 383
  }) : assert(toolbarOpacity != null),
       assert(minExtent != null && minExtent >= 0),
       assert(maxExtent != null && maxExtent >= 0),
       assert(currentExtent != null && currentExtent >= 0),
       assert(toolbarOpacity >= 0.0),
       assert(minExtent <= maxExtent),
       assert(minExtent <= currentExtent),
       assert(currentExtent <= maxExtent),
384
       super(key: key, child: child);
385

386
  /// Affects how transparent the text within the toolbar appears.
387
  final double toolbarOpacity;
388 389

  /// Minimum height of the resulting [FlexibleSpaceBar] when fully collapsed.
390
  final double minExtent;
391 392

  /// Maximum height of the resulting [FlexibleSpaceBar] when fully expanded.
393
  final double maxExtent;
394 395 396 397

  /// 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.
398
  final double currentExtent;
399

400 401 402 403 404 405 406 407 408 409 410
  /// True if the FlexibleSpaceBar overlaps the primary scrollable's contents.
  ///
  /// This value is used by the [AppBar] to resolve
  /// [AppBar.backgroundColor] against [MaterialState.scrolledUnder],
  /// i.e.  to enable apps to specify different colors when content
  /// has been scrolled up and behind the app bar.
  ///
  /// Null if the caller hasn't determined if the FlexibleSpaceBar
  /// overlaps the primary scrollable's contents.
  final bool? isScrolledUnder;

411
  @override
412
  bool updateShouldNotify(FlexibleSpaceBarSettings oldWidget) {
413 414 415
    return toolbarOpacity != oldWidget.toolbarOpacity
        || minExtent != oldWidget.minExtent
        || maxExtent != oldWidget.maxExtent
416 417
        || currentExtent != oldWidget.currentExtent
        || isScrolledUnder != oldWidget.isScrolledUnder;
418
  }
419
}