bottom_tab_bar.dart 10.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
xster's avatar
xster committed
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

xster's avatar
xster committed
7 8 9 10 11
import 'dart:ui' show ImageFilter;

import 'package:flutter/widgets.dart';

import 'colors.dart';
12
import 'localizations.dart';
xster's avatar
xster committed
13
import 'theme.dart';
xster's avatar
xster committed
14 15 16 17

// Standard iOS 10 tab bar height.
const double _kTabBarHeight = 50.0;

18 19 20 21
const Color _kDefaultTabBarBorderColor = CupertinoDynamicColor.withBrightness(
  color: Color(0x4C000000),
  darkColor: Color(0x29000000),
);
22
const Color _kDefaultTabBarInactiveColor = CupertinoColors.inactiveGray;
xster's avatar
xster committed
23

24
/// An iOS-styled bottom navigation tab bar.
25 26 27 28 29 30
///
/// Displays multiple tabs using [BottomNavigationBarItem] with one tab being
/// active, the first tab by default.
///
/// This [StatelessWidget] doesn't store the active tab itself. You must
/// listen to the [onTap] callbacks and call `setState` with a new [currentIndex]
xster's avatar
xster committed
31 32
/// for the new selection to reflect. This can also be done automatically
/// by wrapping this with a [CupertinoTabScaffold].
33 34
///
/// Tab changes typically trigger a switch between [Navigator]s, each with its
xster's avatar
xster committed
35 36
/// own navigation stack, per standard iOS design. This can be done by using
/// [CupertinoTabView]s inside each tab builder in [CupertinoTabScaffold].
37 38 39
///
/// If the given [backgroundColor]'s opacity is not 1.0 (which is the case by
/// default), it will produce a blurring effect to the content behind it.
40
///
41 42 43 44 45 46 47 48
/// When used as [CupertinoTabScaffold.tabBar], by default `CupertinoTabBar` has
/// its text scale factor set to 1.0 and does not respond to text scale factor
/// changes from the operating system, to match the native iOS behavior. To override
/// this behavior, wrap each of the `navigationBar`'s components inside a [MediaQuery]
/// with the desired [MediaQueryData.textScaleFactor] value. The text scale factor
/// value from the operating system can be retrieved in many ways, such as querying
/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext].
///
49 50
/// See also:
///
51 52
///  * [CupertinoTabScaffold], which hosts the [CupertinoTabBar] at the bottom.
///  * [BottomNavigationBarItem], an item in a [CupertinoTabBar].
53
class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget {
54
  /// Creates a tab bar in the iOS style.
55
  const CupertinoTabBar({
xster's avatar
xster committed
56 57 58
    Key key,
    @required this.items,
    this.onTap,
59
    this.currentIndex = 0,
xster's avatar
xster committed
60 61
    this.backgroundColor,
    this.activeColor,
62
    this.inactiveColor = _kDefaultTabBarInactiveColor,
63
    this.iconSize = 30.0,
64 65 66 67 68 69 70
    this.border = const Border(
      top: BorderSide(
        color: _kDefaultTabBarBorderColor,
        width: 0.0, // One physical pixel.
        style: BorderStyle.solid,
      ),
    ),
71
  }) : assert(items != null),
72 73 74 75
       assert(
         items.length >= 2,
         "Tabs need at least 2 items to conform to Apple's HIG",
       ),
76
       assert(currentIndex != null),
77 78
       assert(0 <= currentIndex && currentIndex < items.length),
       assert(iconSize != null),
xster's avatar
xster committed
79
       assert(inactiveColor != null),
80
       super(key: key);
xster's avatar
xster committed
81 82

  /// The interactive items laid out within the bottom navigation bar.
83 84
  ///
  /// Must not be null.
xster's avatar
xster committed
85 86 87 88 89 90 91 92 93 94
  final List<BottomNavigationBarItem> items;

  /// The callback that is called when a item is tapped.
  ///
  /// The widget creating the bottom navigation bar needs to keep track of the
  /// current index and call `setState` to rebuild it with the newly provided
  /// index.
  final ValueChanged<int> onTap;

  /// The index into [items] of the current active item.
95
  ///
96 97
  /// Must not be null and must inclusively be between 0 and the number of tabs
  /// minus 1.
xster's avatar
xster committed
98 99 100 101 102
  final int currentIndex;

  /// The background color of the tab bar. If it contains transparency, the
  /// tab bar will automatically produce a blurring effect to the content
  /// behind it.
xster's avatar
xster committed
103 104
  ///
  /// Defaults to [CupertinoTheme]'s `barBackgroundColor` when null.
xster's avatar
xster committed
105 106 107 108
  final Color backgroundColor;

  /// The foreground color of the icon and title for the [BottomNavigationBarItem]
  /// of the selected tab.
xster's avatar
xster committed
109 110
  ///
  /// Defaults to [CupertinoTheme]'s `primaryColor` if null.
xster's avatar
xster committed
111 112 113 114
  final Color activeColor;

  /// The foreground color of the icon and title for the [BottomNavigationBarItem]s
  /// in the unselected state.
xster's avatar
xster committed
115
  ///
116 117
  /// Defaults to a [CupertinoDynamicColor] that matches the disabled foreground
  /// color of the native `UITabBar` component. Cannot be null.
xster's avatar
xster committed
118 119 120 121
  final Color inactiveColor;

  /// The size of all of the [BottomNavigationBarItem] icons.
  ///
122 123
  /// This value is used to configure the [IconTheme] for the navigation bar.
  /// When a [BottomNavigationBarItem.icon] widget is not an [Icon] the widget
xster's avatar
xster committed
124
  /// should configure itself to match the icon theme's size and color.
125 126
  ///
  /// Must not be null.
xster's avatar
xster committed
127 128
  final double iconSize;

129 130 131 132 133
  /// The border of the [CupertinoTabBar].
  ///
  /// The default value is a one physical pixel top border with grey color.
  final Border border;

xster's avatar
xster committed
134
  @override
135
  Size get preferredSize => const Size.fromHeight(_kTabBarHeight);
xster's avatar
xster committed
136

xster's avatar
xster committed
137 138 139 140 141
  /// Indicates whether the tab bar is fully opaque or can have contents behind
  /// it show through it.
  bool opaque(BuildContext context) {
    final Color backgroundColor =
        this.backgroundColor ?? CupertinoTheme.of(context).barBackgroundColor;
142
    return CupertinoDynamicColor.resolve(backgroundColor, context).alpha == 0xFF;
xster's avatar
xster committed
143 144
  }

145 146
  @override
  Widget build(BuildContext context) {
147
    final double bottomPadding = MediaQuery.of(context).padding.bottom;
xster's avatar
xster committed
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    final Color backgroundColor = CupertinoDynamicColor.resolve(
      this.backgroundColor ?? CupertinoTheme.of(context).barBackgroundColor,
      context,
    );

    BorderSide resolveBorderSide(BorderSide side) {
      return side == BorderSide.none
        ? side
        : side.copyWith(color: CupertinoDynamicColor.resolve(side.color, context));
    }

    // Return the border as is when it's a subclass.
    final Border resolvedBorder = border == null || border.runtimeType != Border
      ? border
      : Border(
        top: resolveBorderSide(border.top),
        left: resolveBorderSide(border.left),
        bottom: resolveBorderSide(border.bottom),
        right: resolveBorderSide(border.right),
      );

    final Color inactive = CupertinoDynamicColor.resolve(inactiveColor, context);
171 172
    Widget result = DecoratedBox(
      decoration: BoxDecoration(
173 174
        border: resolvedBorder,
        color: backgroundColor,
xster's avatar
xster committed
175
      ),
176
      child: SizedBox(
177
        height: _kTabBarHeight + bottomPadding,
xster's avatar
xster committed
178
        child: IconTheme.merge( // Default with the inactive state.
179
          data: IconThemeData(color: inactive, size: iconSize),
180
          child: DefaultTextStyle( // Default with the inactive state.
181
            style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(color: inactive),
182 183
            child: Padding(
              padding: EdgeInsets.only(bottom: bottomPadding),
184 185 186 187 188 189 190
              child: Semantics(
                explicitChildNodes: true,
                child: Row(
                  // Align bottom since we want the labels to be aligned.
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: _buildTabItems(context),
                ),
191
              ),
xster's avatar
xster committed
192 193 194 195 196 197
            ),
          ),
        ),
      ),
    );

xster's avatar
xster committed
198
    if (!opaque(context)) {
xster's avatar
xster committed
199
      // For non-opaque backgrounds, apply a blur effect.
200 201 202
      result = ClipRect(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
xster's avatar
xster committed
203 204 205 206 207 208 209 210
          child: result,
        ),
      );
    }

    return result;
  }

xster's avatar
xster committed
211
  List<Widget> _buildTabItems(BuildContext context) {
xster's avatar
xster committed
212
    final List<Widget> result = <Widget>[];
213 214 215 216 217 218 219 220
    final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
    assert(
      localizations != null,
      'CupertinoTabBar requires a Localizations parent in order to provide an '
        'appropriate Semantics hint for tab indexing. A CupertinoApp will '
        'provide the DefaultCupertinoLocalizations, or you can instantiate your '
        'own Localizations.'
    );
xster's avatar
xster committed
221

222
    for (int index = 0; index < items.length; index += 1) {
223
      final bool active = index == currentIndex;
xster's avatar
xster committed
224 225
      result.add(
        _wrapActiveItem(
xster's avatar
xster committed
226
          context,
227 228
          Expanded(
            child: Semantics(
229
              selected: active,
230 231 232 233
              hint: localizations.tabSemanticsLabel(
                tabIndex: index + 1,
                tabCount: items.length,
              ),
234
              child: GestureDetector(
235 236
                behavior: HitTestBehavior.opaque,
                onTap: onTap == null ? null : () { onTap(index); },
237
                child: Padding(
238
                  padding: const EdgeInsets.only(bottom: 4.0),
239
                  child: Column(
240
                    mainAxisAlignment: MainAxisAlignment.end,
241
                    children: _buildSingleTabItem(items[index], active),
242
                  ),
xster's avatar
xster committed
243 244 245 246
                ),
              ),
            ),
          ),
247
          active: active,
xster's avatar
xster committed
248 249 250 251 252 253 254
        ),
      );
    }

    return result;
  }

255
  List<Widget> _buildSingleTabItem(BottomNavigationBarItem item, bool active) {
256
    return <Widget>[
257 258
      Expanded(
        child: Center(child: active ? item.activeIcon : item.icon),
259
      ),
260
      if (item.title != null) item.title,
261 262 263
    ];
  }

xster's avatar
xster committed
264
  /// Change the active tab item's icon and title colors to active.
xster's avatar
xster committed
265
  Widget _wrapActiveItem(BuildContext context, Widget item, { @required bool active }) {
xster's avatar
xster committed
266 267 268
    if (!active)
      return item;

269 270 271 272
    final Color activeColor = CupertinoDynamicColor.resolve(
      this.activeColor ?? CupertinoTheme.of(context).primaryColor,
      context,
    );
xster's avatar
xster committed
273
    return IconTheme.merge(
274
      data: IconThemeData(color: activeColor),
xster's avatar
xster committed
275
      child: DefaultTextStyle.merge(
276
        style: TextStyle(color: activeColor),
xster's avatar
xster committed
277 278 279 280
        child: item,
      ),
    );
  }
281 282

  /// Create a clone of the current [CupertinoTabBar] but with provided
283
  /// parameters overridden.
284 285 286 287 288 289
  CupertinoTabBar copyWith({
    Key key,
    List<BottomNavigationBarItem> items,
    Color backgroundColor,
    Color activeColor,
    Color inactiveColor,
290
    double iconSize,
291
    Border border,
292 293 294
    int currentIndex,
    ValueChanged<int> onTap,
  }) {
295
    return CupertinoTabBar(
296 297 298 299 300 301 302 303 304
      key: key ?? this.key,
      items: items ?? this.items,
      backgroundColor: backgroundColor ?? this.backgroundColor,
      activeColor: activeColor ?? this.activeColor,
      inactiveColor: inactiveColor ?? this.inactiveColor,
      iconSize: iconSize ?? this.iconSize,
      border: border ?? this.border,
      currentIndex: currentIndex ?? this.currentIndex,
      onTap: onTap ?? this.onTap,
305 306
    );
  }
xster's avatar
xster committed
307
}