bottom_tab_bar.dart 9.92 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 5 6 7 8 9
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:ui' show ImageFilter;

import 'package:flutter/widgets.dart';

import 'colors.dart';
xster's avatar
xster committed
10
import 'theme.dart';
xster's avatar
xster committed
11 12 13 14

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

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

21
/// An iOS-styled bottom navigation tab bar.
22 23 24 25 26 27
///
/// 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
28 29
/// for the new selection to reflect. This can also be done automatically
/// by wrapping this with a [CupertinoTabScaffold].
30 31
///
/// Tab changes typically trigger a switch between [Navigator]s, each with its
xster's avatar
xster committed
32 33
/// own navigation stack, per standard iOS design. This can be done by using
/// [CupertinoTabView]s inside each tab builder in [CupertinoTabScaffold].
34 35 36
///
/// 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.
37
///
38 39 40 41 42 43 44 45
/// 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].
///
46 47
/// See also:
///
48 49
///  * [CupertinoTabScaffold], which hosts the [CupertinoTabBar] at the bottom.
///  * [BottomNavigationBarItem], an item in a [CupertinoTabBar].
50
class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget {
51
  /// Creates a tab bar in the iOS style.
52
  const CupertinoTabBar({
xster's avatar
xster committed
53 54 55
    Key key,
    @required this.items,
    this.onTap,
56
    this.currentIndex = 0,
xster's avatar
xster committed
57 58
    this.backgroundColor,
    this.activeColor,
59
    this.inactiveColor = _kDefaultTabBarInactiveColor,
60
    this.iconSize = 30.0,
61 62 63 64 65 66 67
    this.border = const Border(
      top: BorderSide(
        color: _kDefaultTabBarBorderColor,
        width: 0.0, // One physical pixel.
        style: BorderStyle.solid,
      ),
    ),
68
  }) : assert(items != null),
69 70 71 72
       assert(
         items.length >= 2,
         "Tabs need at least 2 items to conform to Apple's HIG",
       ),
73
       assert(currentIndex != null),
74 75
       assert(0 <= currentIndex && currentIndex < items.length),
       assert(iconSize != null),
xster's avatar
xster committed
76
       assert(inactiveColor != null),
77
       super(key: key);
xster's avatar
xster committed
78 79

  /// The interactive items laid out within the bottom navigation bar.
80 81
  ///
  /// Must not be null.
xster's avatar
xster committed
82 83 84 85 86 87 88 89 90 91
  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.
92
  ///
93 94
  /// Must not be null and must inclusively be between 0 and the number of tabs
  /// minus 1.
xster's avatar
xster committed
95 96 97 98 99
  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
100 101
  ///
  /// Defaults to [CupertinoTheme]'s `barBackgroundColor` when null.
xster's avatar
xster committed
102 103 104 105
  final Color backgroundColor;

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

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

  /// The size of all of the [BottomNavigationBarItem] icons.
  ///
119 120
  /// 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
121
  /// should configure itself to match the icon theme's size and color.
122 123
  ///
  /// Must not be null.
xster's avatar
xster committed
124 125
  final double iconSize;

126 127 128 129 130
  /// 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
131
  @override
132
  Size get preferredSize => const Size.fromHeight(_kTabBarHeight);
xster's avatar
xster committed
133

xster's avatar
xster committed
134 135 136 137 138
  /// 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;
139
    return CupertinoDynamicColor.resolve(backgroundColor, context).alpha == 0xFF;
xster's avatar
xster committed
140 141
  }

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

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    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);
168 169
    Widget result = DecoratedBox(
      decoration: BoxDecoration(
170 171
        border: resolvedBorder,
        color: backgroundColor,
xster's avatar
xster committed
172
      ),
173
      child: SizedBox(
174
        height: _kTabBarHeight + bottomPadding,
xster's avatar
xster committed
175
        child: IconTheme.merge( // Default with the inactive state.
176
          data: IconThemeData(color: inactive, size: iconSize),
177
          child: DefaultTextStyle( // Default with the inactive state.
178
            style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(color: inactive),
179 180 181
            child: Padding(
              padding: EdgeInsets.only(bottom: bottomPadding),
              child: Row(
182 183
                // Align bottom since we want the labels to be aligned.
                crossAxisAlignment: CrossAxisAlignment.end,
xster's avatar
xster committed
184
                children: _buildTabItems(context),
185
              ),
xster's avatar
xster committed
186 187 188 189 190 191
            ),
          ),
        ),
      ),
    );

xster's avatar
xster committed
192
    if (!opaque(context)) {
xster's avatar
xster committed
193
      // For non-opaque backgrounds, apply a blur effect.
194 195 196
      result = ClipRect(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
xster's avatar
xster committed
197 198 199 200 201 202 203 204
          child: result,
        ),
      );
    }

    return result;
  }

xster's avatar
xster committed
205
  List<Widget> _buildTabItems(BuildContext context) {
xster's avatar
xster committed
206 207
    final List<Widget> result = <Widget>[];

208
    for (int index = 0; index < items.length; index += 1) {
209
      final bool active = index == currentIndex;
xster's avatar
xster committed
210 211
      result.add(
        _wrapActiveItem(
xster's avatar
xster committed
212
          context,
213 214
          Expanded(
            child: Semantics(
215
              selected: active,
216
              // TODO(xster): This needs localization support. https://github.com/flutter/flutter/issues/13452
217
              hint: 'tab, ${index + 1} of ${items.length}',
218
              child: GestureDetector(
219 220
                behavior: HitTestBehavior.opaque,
                onTap: onTap == null ? null : () { onTap(index); },
221
                child: Padding(
222
                  padding: const EdgeInsets.only(bottom: 4.0),
223
                  child: Column(
224
                    mainAxisAlignment: MainAxisAlignment.end,
225
                    children: _buildSingleTabItem(items[index], active),
226
                  ),
xster's avatar
xster committed
227 228 229 230
                ),
              ),
            ),
          ),
231
          active: active,
xster's avatar
xster committed
232 233 234 235 236 237 238
        ),
      );
    }

    return result;
  }

239
  List<Widget> _buildSingleTabItem(BottomNavigationBarItem item, bool active) {
240
    return <Widget>[
241 242
      Expanded(
        child: Center(child: active ? item.activeIcon : item.icon),
243
      ),
244
      if (item.title != null) item.title,
245 246 247
    ];
  }

xster's avatar
xster committed
248
  /// Change the active tab item's icon and title colors to active.
xster's avatar
xster committed
249
  Widget _wrapActiveItem(BuildContext context, Widget item, { @required bool active }) {
xster's avatar
xster committed
250 251 252
    if (!active)
      return item;

253 254 255 256
    final Color activeColor = CupertinoDynamicColor.resolve(
      this.activeColor ?? CupertinoTheme.of(context).primaryColor,
      context,
    );
xster's avatar
xster committed
257
    return IconTheme.merge(
258
      data: IconThemeData(color: activeColor),
xster's avatar
xster committed
259
      child: DefaultTextStyle.merge(
260
        style: TextStyle(color: activeColor),
xster's avatar
xster committed
261 262 263 264
        child: item,
      ),
    );
  }
265 266

  /// Create a clone of the current [CupertinoTabBar] but with provided
267
  /// parameters overridden.
268 269 270 271 272 273
  CupertinoTabBar copyWith({
    Key key,
    List<BottomNavigationBarItem> items,
    Color backgroundColor,
    Color activeColor,
    Color inactiveColor,
274
    double iconSize,
275
    Border border,
276 277 278
    int currentIndex,
    ValueChanged<int> onTap,
  }) {
279
    return CupertinoTabBar(
280 281 282 283 284 285 286 287 288
      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,
289 290
    );
  }
xster's avatar
xster committed
291
}