navigation_bar_theme_test.dart 14.3 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8 9
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;

10
import 'package:flutter/foundation.dart';
11
import 'package:flutter/gestures.dart';
12 13
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
14
import 'package:flutter/services.dart';
15
import 'package:flutter_test/flutter_test.dart';
16

17 18 19 20 21 22
void main() {
  test('copyWith, ==, hashCode basics', () {
    expect(const NavigationBarThemeData(), const NavigationBarThemeData().copyWith());
    expect(const NavigationBarThemeData().hashCode, const NavigationBarThemeData().copyWith().hashCode);
  });

23 24 25 26 27 28
  test('NavigationBarThemeData lerp special cases', () {
    expect(NavigationBarThemeData.lerp(null, null, 0), null);
    const NavigationBarThemeData data = NavigationBarThemeData();
    expect(identical(NavigationBarThemeData.lerp(data, data, 0.5), data), true);
  });

29
  testWidgets('Default debugFillProperties', (WidgetTester tester) async {
30 31 32 33 34 35 36 37 38 39 40
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
    const NavigationBarThemeData().debugFillProperties(builder);

    final List<String> description = builder.properties
        .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
        .map((DiagnosticsNode node) => node.toString())
        .toList();

    expect(description, <String>[]);
  });

41
  testWidgets('Custom debugFillProperties', (WidgetTester tester) async {
42
    final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
43
    const NavigationBarThemeData(
44
      height: 200.0,
45
      backgroundColor: Color(0x00000099),
46
      elevation: 20.0,
47 48 49 50
      indicatorColor: Color(0x00000098),
      indicatorShape: CircleBorder(),
      labelTextStyle: MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)),
      iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: Color(0x00000097))),
51
      labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
52
      overlayColor: MaterialStatePropertyAll<Color>(Color(0x00000096)),
53 54 55 56 57 58 59 60 61
    ).debugFillProperties(builder);

    final List<String> description = builder.properties
        .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
        .map((DiagnosticsNode node) => node.toString())
        .toList();

    expect(description[0], 'height: 200.0');
    expect(description[1], 'backgroundColor: Color(0x00000099)');
62 63
    expect(description[2], 'elevation: 20.0');
    expect(description[3], 'indicatorColor: Color(0x00000098)');
64
    expect(description[4], 'indicatorShape: CircleBorder(BorderSide(width: 0.0, style: none))');
65
    expect(description[5], 'labelTextStyle: MaterialStatePropertyAll(TextStyle(inherit: true, size: 7.0))');
66
    // Ignore instance address for IconThemeData.
67
    expect(description[6].contains('iconTheme: MaterialStatePropertyAll(IconThemeData'), isTrue);
68 69
    expect(description[6].contains('(color: Color(0x00000097))'), isTrue);
    expect(description[7], 'labelBehavior: NavigationDestinationLabelBehavior.alwaysHide');
70
    expect(description[8], 'overlayColor: MaterialStatePropertyAll(Color(0x00000096))');
71 72
  });

73
  testWidgets('NavigationBarThemeData values are used when no NavigationBar properties are specified', (WidgetTester tester) async {
74 75
    const double height = 200.0;
    const Color backgroundColor = Color(0x00000001);
76
    const double elevation = 42.0;
77
    const Color indicatorColor = Color(0x00000002);
78
    const ShapeBorder indicatorShape = CircleBorder();
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    const double selectedIconSize = 25.0;
    const double unselectedIconSize = 23.0;
    const Color selectedIconColor = Color(0x00000003);
    const Color unselectedIconColor = Color(0x00000004);
    const double selectedIconOpacity = 0.99;
    const double unselectedIconOpacity = 0.98;
    const double selectedLabelFontSize = 13.0;
    const double unselectedLabelFontSize = 11.0;
    const NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow;

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          bottomNavigationBar: NavigationBarTheme(
            data: NavigationBarThemeData(
              height: height,
              backgroundColor: backgroundColor,
96
              elevation: elevation,
97
              indicatorColor: indicatorColor,
98
              indicatorShape: indicatorShape,
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
              iconTheme: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
                if (states.contains(MaterialState.selected)) {
                  return const IconThemeData(
                    size: selectedIconSize,
                    color: selectedIconColor,
                    opacity: selectedIconOpacity,
                  );
                }
                return const IconThemeData(
                  size: unselectedIconSize,
                  color: unselectedIconColor,
                  opacity: unselectedIconOpacity,
                );
              }),
              labelTextStyle: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
                if (states.contains(MaterialState.selected)) {
                  return const TextStyle(fontSize: selectedLabelFontSize);
                }
                return const TextStyle(fontSize: unselectedLabelFontSize);
              }),
              labelBehavior: labelBehavior,
            ),
            child: NavigationBar(
              destinations: _destinations(),
            ),
          ),
        ),
      ),
    );

    expect(_barHeight(tester), height);
    expect(_barMaterial(tester).color, backgroundColor);
131
    expect(_barMaterial(tester).elevation, elevation);
132
    expect(_indicator(tester)?.color, indicatorColor);
133
    expect(_indicator(tester)?.shape, indicatorShape);
134 135 136 137 138 139 140 141 142 143 144
    expect(_selectedIconTheme(tester).size, selectedIconSize);
    expect(_selectedIconTheme(tester).color, selectedIconColor);
    expect(_selectedIconTheme(tester).opacity, selectedIconOpacity);
    expect(_unselectedIconTheme(tester).size, unselectedIconSize);
    expect(_unselectedIconTheme(tester).color, unselectedIconColor);
    expect(_unselectedIconTheme(tester).opacity, unselectedIconOpacity);
    expect(_selectedLabelStyle(tester).fontSize, selectedLabelFontSize);
    expect(_unselectedLabelStyle(tester).fontSize, unselectedLabelFontSize);
    expect(_labelBehavior(tester), labelBehavior);
  });

145
  testWidgets('NavigationBar values take priority over NavigationBarThemeData values when both properties are specified', (WidgetTester tester) async {
146 147
    const double height = 200.0;
    const Color backgroundColor = Color(0x00000001);
148
    const double elevation = 42.0;
149 150 151 152 153 154 155 156
    const NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow;

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          bottomNavigationBar: NavigationBarTheme(
            data: const NavigationBarThemeData(
              height: 100.0,
157
              elevation: 18.0,
158 159 160 161 162
              backgroundColor: Color(0x00000099),
              labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
            ),
            child: NavigationBar(
              height: height,
163
              elevation: elevation,
164 165 166 167 168 169 170 171 172 173 174
              backgroundColor: backgroundColor,
              labelBehavior: labelBehavior,
              destinations: _destinations(),
            ),
          ),
        ),
      ),
    );

    expect(_barHeight(tester), height);
    expect(_barMaterial(tester).color, backgroundColor);
175
    expect(_barMaterial(tester).elevation, elevation);
176 177
    expect(_labelBehavior(tester), labelBehavior);
  });
178

179
  testWidgets('Custom label style renders ink ripple properly', (WidgetTester tester) async {
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    Widget buildWidget({ NavigationDestinationLabelBehavior? labelBehavior }) {
      return MaterialApp(
        theme: ThemeData(
          navigationBarTheme: const NavigationBarThemeData(
            labelTextStyle: MaterialStatePropertyAll<TextStyle>(
              TextStyle(fontSize: 25, color: Color(0xff0000ff)),
            ),
          ),
          useMaterial3: true,
        ),
        home: Scaffold(
          bottomNavigationBar: Center(
            child: NavigationBar(
              labelBehavior: labelBehavior,
              destinations: const <Widget>[
                NavigationDestination(
                  icon: SizedBox(),
                  label: 'AC',
                ),
                NavigationDestination(
                  icon: SizedBox(),
                  label: 'Alarm',
                ),
              ],
              onDestinationSelected: (int i) { },
            ),
          ),
        ),
      );
    }

    await tester.pumpWidget(buildWidget());

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
    await gesture.addPointer();
    await gesture.moveTo(tester.getCenter(find.byType(NavigationDestination).last));
    await tester.pumpAndSettle();

    await expectLater(find.byType(NavigationBar), matchesGoldenFile('indicator_custom_label_style.png'));
  });
220

221
  testWidgets('NavigationBar respects NavigationBarTheme.overlayColor in active/pressed/hovered states', (WidgetTester tester) async {
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
    const Color hoverColor = Color(0xff0000ff);
    const Color focusColor = Color(0xff00ffff);
    const Color pressedColor = Color(0xffff00ff);
    final MaterialStateProperty<Color?> overlayColor = MaterialStateProperty.resolveWith<Color>(
      (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered)) {
          return hoverColor;
        }
        if (states.contains(MaterialState.focused)) {
          return focusColor;
        }
        if (states.contains(MaterialState.pressed)) {
          return pressedColor;
        }
        return Colors.transparent;
    });

    await tester.pumpWidget(MaterialApp(
      theme: ThemeData(navigationBarTheme: NavigationBarThemeData(overlayColor: overlayColor)),
      home: Scaffold(
        bottomNavigationBar: RepaintBoundary(
          child: NavigationBar(
            destinations: const <Widget>[
              NavigationDestination(
                icon: Icon(Icons.ac_unit),
                label: 'AC',
              ),
              NavigationDestination(
                icon: Icon(Icons.access_alarm),
                label: 'Alarm',
              ),
            ],
            onDestinationSelected: (int i) { },
          ),
        ),
      ),
    ));

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
    await gesture.addPointer();
    await gesture.moveTo(tester.getCenter(find.byType(NavigationIndicator).last));
    await tester.pumpAndSettle();

    final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');

    // Test hovered state.
    expect(
      inkFeatures,
      kIsWeb
        ? (paints..rrect()..rrect()..circle(color: hoverColor))
        : (paints..circle(color: hoverColor)),
    );

    await gesture.down(tester.getCenter(find.byType(NavigationIndicator).last));
    await tester.pumpAndSettle();

    // Test pressed state.
    expect(
      inkFeatures,
      kIsWeb
        ? (paints..circle()..circle()..circle(color: pressedColor))
        : (paints..circle()..circle(color: pressedColor)),
    );

    await gesture.up();
    await tester.pumpAndSettle();

    // Press tab to focus the navigation bar.
    await tester.sendKeyEvent(LogicalKeyboardKey.tab);
    await tester.pumpAndSettle();

    // Test focused state.
    expect(
      inkFeatures,
      kIsWeb ? (paints..circle()..circle(color: focusColor)) : (paints..circle()..circle(color: focusColor)),
    );
  });
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
}

List<NavigationDestination> _destinations() {
  return const <NavigationDestination>[
    NavigationDestination(
      icon: Icon(Icons.favorite_border),
      selectedIcon: Icon(Icons.favorite),
      label: 'Abc',
    ),
    NavigationDestination(
      icon: Icon(Icons.star_border),
      selectedIcon: Icon(Icons.star),
      label: 'Def',
    ),
  ];
}

double _barHeight(WidgetTester tester) {
  return tester.getRect(
    find.byType(NavigationBar),
  ).height;
}

Material _barMaterial(WidgetTester tester) {
  return tester.firstWidget<Material>(
    find.descendant(
      of: find.byType(NavigationBar),
      matching: find.byType(Material),
    ),
  );
}

332
ShapeDecoration? _indicator(WidgetTester tester) {
333 334 335 336 337
  return tester.firstWidget<Container>(
    find.descendant(
      of: find.byType(FadeTransition),
      matching: find.byType(Container),
    ),
338
  ).decoration as ShapeDecoration?;
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 401 402
}

IconThemeData _selectedIconTheme(WidgetTester tester) {
  return _iconTheme(tester, Icons.favorite);
}

IconThemeData _unselectedIconTheme(WidgetTester tester) {
  return _iconTheme(tester, Icons.star_border);
}

IconThemeData _iconTheme(WidgetTester tester, IconData icon) {
  return tester.firstWidget<IconTheme>(
    find.ancestor(
      of: find.byIcon(icon),
      matching: find.byType(IconTheme),
    ),
  ).data;
}

TextStyle _selectedLabelStyle(WidgetTester tester) {
  return tester.widget<RichText>(
    find.descendant(
      of: find.text('Abc'),
      matching: find.byType(RichText),
    ),
  ).text.style!;
}

TextStyle _unselectedLabelStyle(WidgetTester tester) {
  return tester.widget<RichText>(
    find.descendant(
      of: find.text('Def'),
      matching: find.byType(RichText),
    ),
  ).text.style!;
}

NavigationDestinationLabelBehavior _labelBehavior(WidgetTester tester) {
  if (_opacityAboveLabel('Abc').evaluate().isNotEmpty && _opacityAboveLabel('Def').evaluate().isNotEmpty) {
    return _labelOpacity(tester, 'Abc') == 1
        ? NavigationDestinationLabelBehavior.onlyShowSelected
        : NavigationDestinationLabelBehavior.alwaysHide;
  } else {
    return NavigationDestinationLabelBehavior.alwaysShow;
  }
}

Finder _opacityAboveLabel(String text) {
  return find.ancestor(
    of: find.text(text),
    matching: find.byType(Opacity),
  );
}

// Only valid when labelBehavior != alwaysShow.
double _labelOpacity(WidgetTester tester, String text) {
  final Opacity opacityWidget = tester.widget<Opacity>(
    find.ancestor(
      of: find.text(text),
      matching: find.byType(Opacity),
    ),
  );
  return opacityWidget.opacity;
}