flexible_space_bar.dart 15.5 KB
Newer Older
1 2 3 4 5
// 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;
6
import 'dart:ui' as ui;
7

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

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

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

27 28 29 30 31 32 33 34 35 36 37 38 39 40
/// 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.
41
///
42 43 44
/// 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
45 46 47
/// app. Furthermore is included functionality for stretch behavior. When
/// [SliverAppBar.stretch] is true, and your [ScrollPhysics] allow for
/// overscroll, this space will stretch with the overscroll.
48
///
49 50 51
/// The widget that sizes the [AppBar] must wrap it in the widget returned by
/// [FlexibleSpaceBar.createSettings], to convey sizing information down to the
/// [FlexibleSpaceBar].
52
///
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
/// {@tool snippet --template=freeform}
/// 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.
///
/// ```dart imports
/// import 'package:flutter/material.dart';
/// ```
/// ```dart
/// void main() => runApp(MaterialApp(home: MyApp()));
///
/// class MyApp extends StatelessWidget {
///   @override
///   Widget build(BuildContext context) {
///     return Scaffold(
///       body: CustomScrollView(
///         physics: const BouncingScrollPhysics(),
///         slivers: <Widget>[
///           SliverAppBar(
///             stretch: true,
///             onStretchTrigger: () {
///               // Function callback for stretch
///               return;
///             },
///             expandedHeight: 300.0,
///             flexibleSpace: FlexibleSpaceBar(
///               stretchModes: <StretchMode>[
///                 StretchMode.zoomBackground,
///                 StretchMode.blurBackground,
///                 StretchMode.fadeTitle,
///               ],
///               centerTitle: true,
///               title: const Text('Flight Report'),
///               background: Stack(
///                 fit: StackFit.expand,
///                 children: [
///                   Image.network(
///                     'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg',
///                     fit: BoxFit.cover,
///                   ),
///                   const DecoratedBox(
///                     decoration: BoxDecoration(
///                       gradient: LinearGradient(
///                         begin: Alignment(0.0, 0.5),
///                         end: Alignment(0.0, 0.0),
///                         colors: <Color>[
///                           Color(0x60000000),
///                           Color(0x00000000),
///                         ],
///                       ),
///                     ),
///                   ),
///                 ],
///               ),
///             ),
///           ),
///           SliverList(
///             delegate: SliverChildListDelegate([
///               ListTile(
///                 leading: Icon(Icons.wb_sunny),
///                 title: Text('Sunday'),
///                 subtitle: Text('sunny, h: 80, l: 65'),
///               ),
///               ListTile(
///                 leading: Icon(Icons.wb_sunny),
///                 title: Text('Monday'),
///                 subtitle: Text('sunny, h: 80, l: 65'),
///               ),
///               // ListTiles++
///             ]),
///           ),
///         ],
///       ),
///     );
///   }
/// }
///
/// ```
/// {@end-tool}
///
136
/// See also:
Ian Hickson's avatar
Ian Hickson committed
137
///
138 139
///  * [SliverAppBar], which implements the expanding and contracting.
///  * [AppBar], which is used by [SliverAppBar].
140
///  * <https://material.io/design/components/app-bars-top.html#behavior>
141
class FlexibleSpaceBar extends StatefulWidget {
142 143
  /// Creates a flexible space bar.
  ///
144
  /// Most commonly used in the [AppBar.flexibleSpace] field.
145
  const FlexibleSpaceBar({
146 147 148
    Key key,
    this.title,
    this.background,
149
    this.centerTitle,
150
    this.titlePadding,
151
    this.collapseMode = CollapseMode.parallax,
152
    this.stretchModes = const <StretchMode>[StretchMode.zoomBackground],
153 154
  }) : assert(collapseMode != null),
       super(key: key);
155

156 157 158
  /// The primary contents of the flexible space bar when expanded.
  ///
  /// Typically a [Text] widget.
159
  final Widget title;
160 161 162

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

166 167
  /// Whether the title should be centered.
  ///
168 169
  /// By default this property is true if the current target platform
  /// is [TargetPlatform.iOS], false otherwise.
170 171
  final bool centerTitle;

172 173 174 175 176
  /// Collapse effect while scrolling.
  ///
  /// Defaults to [CollapseMode.parallax].
  final CollapseMode collapseMode;

177 178 179 180 181
  /// Stretch effect while over-scrolling,
  ///
  /// Defaults to include [StretchMode.zoomBackground].
  final List<StretchMode> stretchModes;

182 183 184 185 186 187 188 189 190 191 192 193
  /// 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
  /// not centered, `EdgeInsetsDirectional.only(start 0, bottom: 16)` otherwise.
  final EdgeInsetsGeometry titlePadding;

194 195 196 197
  /// Wraps a widget that contains an [AppBar] to convey sizing information down
  /// to the [FlexibleSpaceBar].
  ///
  /// Used by [Scaffold] and [SliverAppBar].
198 199 200 201 202 203 204 205 206 207 208
  ///
  /// `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:
  ///
209 210
  ///  * [FlexibleSpaceBarSettings] which creates a settings object that can be
  ///    used to specify these settings to a [FlexibleSpaceBar].
211 212 213 214 215 216 217 218
  static Widget createSettings({
    double toolbarOpacity,
    double minExtent,
    double maxExtent,
    @required double currentExtent,
    @required Widget child,
  }) {
    assert(currentExtent != null);
219
    return FlexibleSpaceBarSettings(
220 221 222 223 224 225 226 227
      toolbarOpacity: toolbarOpacity ?? 1.0,
      minExtent: minExtent ?? currentExtent,
      maxExtent: maxExtent ?? currentExtent,
      currentExtent: currentExtent,
      child: child,
    );
  }

228
  @override
229
  _FlexibleSpaceBarState createState() => _FlexibleSpaceBarState();
230 231 232
}

class _FlexibleSpaceBarState extends State<FlexibleSpaceBar> {
233
  bool _getEffectiveCenterTitle(ThemeData theme) {
234 235
    if (widget.centerTitle != null)
      return widget.centerTitle;
236 237 238
    assert(theme.platform != null);
    switch (theme.platform) {
      case TargetPlatform.android:
239
      case TargetPlatform.fuchsia:
240 241 242 243
        return false;
      case TargetPlatform.iOS:
        return true;
    }
244
    return null;
245 246
  }

247
  Alignment _getTitleAlignment(bool effectiveCenterTitle) {
248
    if (effectiveCenterTitle)
249
      return Alignment.bottomCenter;
250 251 252 253
    final TextDirection textDirection = Directionality.of(context);
    assert(textDirection != null);
    switch (textDirection) {
      case TextDirection.rtl:
254
        return Alignment.bottomRight;
255
      case TextDirection.ltr:
256
        return Alignment.bottomLeft;
257 258 259 260
    }
    return null;
  }

261
  double _getCollapsePadding(double t, FlexibleSpaceBarSettings settings) {
262 263 264 265 266 267 268
    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;
269
        return -Tween<double>(begin: 0.0, end: deltaExtent / 4.0).transform(t);
270 271 272 273
    }
    return null;
  }

274 275
  @override
  Widget build(BuildContext context) {
276 277 278 279 280 281 282
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final FlexibleSpaceBarSettings settings = context.inheritFromWidgetOfExactType(FlexibleSpaceBarSettings);
        assert(
          settings != null,
          'A FlexibleSpaceBar must be wrapped in the widget returned by FlexibleSpaceBar.createSettings().',
        );
283

284
        final List<Widget> children = <Widget>[];
285

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        final double deltaExtent = settings.maxExtent - settings.minExtent;

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

        // background
        if (widget.background != null) {
          final double fadeStart = math.max(0.0, 1.0 - kToolbarHeight / deltaExtent);
          const double fadeEnd = 1.0;
          assert(fadeStart <= fadeEnd);
          final double opacity = 1.0 - Interval(fadeStart, fadeEnd).transform(t);
          if (opacity > 0.0) {
            double height = settings.maxExtent;

            // 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(
                opacity: opacity,
                child: widget.background,
315
              ),
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            ));

            // 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(
                  child: Container(
                    color: Colors.transparent,
                  ),
                  filter: ui.ImageFilter.blur(
                    sigmaX: blurAmount,
                    sigmaY: blurAmount,
                  )
                )
              ));
            }
          }
        }
336

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        // title
        if (widget.title != null) {
          final ThemeData theme = Theme.of(context);

          Widget title;
          switch (theme.platform) {
            case TargetPlatform.iOS:
              title = widget.title;
              break;
            case TargetPlatform.fuchsia:
            case TargetPlatform.android:
              title = Semantics(
                namesRoute: true,
                child: widget.title,
              );
          }

          // StretchMode.fadeTitle
          if (widget.stretchModes.contains(StretchMode.fadeTitle) &&
            constraints.maxHeight > settings.maxExtent) {
            final double stretchOpacity = 1 -
              ((constraints.maxHeight - settings.maxExtent) / 100).clamp(0.0, 1.0);
            title = Opacity(
              opacity: stretchOpacity,
              child: title,
            );
          }

          final double opacity = settings.toolbarOpacity;
          if (opacity > 0.0) {
            TextStyle titleStyle = theme.primaryTextTheme.title;
            titleStyle = titleStyle.copyWith(
              color: titleStyle.color.withOpacity(opacity)
            );
            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,
                    child: title,
                  ),
                ),
              ),
            ));
          }
        }

        return ClipRect(child: Stack(children: children));
      }
    );
401
  }
402 403
}

404 405 406 407
/// Provides sizing and opacity information to a [FlexibleSpaceBar].
///
/// See also:
///
408
///  * [FlexibleSpaceBar] which creates a flexible space bar.
409 410 411 412 413
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.
414 415 416
  ///
  /// The required [toolbarOpacity], [minExtent], [maxExtent], [currentExtent],
  /// and [child] parameters must not be null.
417
  const FlexibleSpaceBarSettings({
418
    Key key,
419 420 421
    @required this.toolbarOpacity,
    @required this.minExtent,
    @required this.maxExtent,
422 423
    @required this.currentExtent,
    @required Widget child,
424 425 426 427 428 429 430 431
  }) : 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),
432
       super(key: key, child: child);
433

434
  /// Affects how transparent the text within the toolbar appears.
435
  final double toolbarOpacity;
436 437

  /// Minimum height of the resulting [FlexibleSpaceBar] when fully collapsed.
438
  final double minExtent;
439 440

  /// Maximum height of the resulting [FlexibleSpaceBar] when fully expanded.
441
  final double maxExtent;
442 443 444 445

  /// 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.
446
  final double currentExtent;
447 448

  @override
449
  bool updateShouldNotify(FlexibleSpaceBarSettings oldWidget) {
450 451 452 453
    return toolbarOpacity != oldWidget.toolbarOpacity
        || minExtent != oldWidget.minExtent
        || maxExtent != oldWidget.maxExtent
        || currentExtent != oldWidget.currentExtent;
454
  }
455
}