bottom_tab_bar.dart 10.2 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';
10
import 'localizations.dart';
xster's avatar
xster committed
11
import 'theme.dart';
xster's avatar
xster committed
12 13 14 15

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

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

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

  /// The interactive items laid out within the bottom navigation bar.
81 82
  ///
  /// Must not be null.
xster's avatar
xster committed
83 84 85 86 87 88 89
  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.
90
  final ValueChanged<int>? onTap;
xster's avatar
xster committed
91 92

  /// The index into [items] of the current active item.
93
  ///
94 95
  /// Must not be null and must inclusively be between 0 and the number of tabs
  /// minus 1.
xster's avatar
xster committed
96 97 98 99 100
  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
101 102
  ///
  /// Defaults to [CupertinoTheme]'s `barBackgroundColor` when null.
103
  final Color? backgroundColor;
xster's avatar
xster committed
104 105 106

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

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

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

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

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

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

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

148
    final Color backgroundColor = CupertinoDynamicColor.resolve(
149 150 151 152 153 154 155 156 157 158 159
      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.
160
    final Border? resolvedBorder = border == null || border.runtimeType != Border
161 162
      ? border
      : Border(
163 164 165 166
        top: resolveBorderSide(border!.top),
        left: resolveBorderSide(border!.left),
        bottom: resolveBorderSide(border!.bottom),
        right: resolveBorderSide(border!.right),
167 168
      );

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

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

    return result;
  }

xster's avatar
xster committed
210
  List<Widget> _buildTabItems(BuildContext context) {
xster's avatar
xster committed
211
    final List<Widget> result = <Widget>[];
212
    final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
xster's avatar
xster committed
213

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

    return result;
  }

247
  List<Widget> _buildSingleTabItem(BottomNavigationBarItem item, bool active) {
248
    return <Widget>[
249 250
      Expanded(
        child: Center(child: active ? item.activeIcon : item.icon),
251
      ),
252 253
      if (item.title != null) item.title!,
      if (item.label != null) Text(item.label!),
254 255 256
    ];
  }

xster's avatar
xster committed
257
  /// Change the active tab item's icon and title colors to active.
258
  Widget _wrapActiveItem(BuildContext context, Widget item, { required bool active }) {
xster's avatar
xster committed
259 260 261
    if (!active)
      return item;

262
    final Color activeColor = CupertinoDynamicColor.resolve(
263 264 265
      this.activeColor ?? CupertinoTheme.of(context).primaryColor,
      context,
    );
xster's avatar
xster committed
266
    return IconTheme.merge(
267
      data: IconThemeData(color: activeColor),
xster's avatar
xster committed
268
      child: DefaultTextStyle.merge(
269
        style: TextStyle(color: activeColor),
xster's avatar
xster committed
270 271 272 273
        child: item,
      ),
    );
  }
274 275

  /// Create a clone of the current [CupertinoTabBar] but with provided
276
  /// parameters overridden.
277
  CupertinoTabBar copyWith({
278 279 280 281 282 283 284 285 286
    Key? key,
    List<BottomNavigationBarItem>? items,
    Color? backgroundColor,
    Color? activeColor,
    Color? inactiveColor,
    double? iconSize,
    Border? border,
    int? currentIndex,
    ValueChanged<int>? onTap,
287
  }) {
288
    return CupertinoTabBar(
289 290 291 292 293 294 295 296 297
      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,
298 299
    );
  }
xster's avatar
xster committed
300
}