theme_test.dart 17.1 KB
Newer Older
1 2 3 4
// 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.

5
import 'dart:ui' as ui;
6
import 'package:flutter/material.dart';
7
import 'package:flutter/rendering.dart';
8
import 'package:flutter/src/foundation/diagnostics.dart';
9 10 11
import 'package:flutter_test/flutter_test.dart';

void main() {
12
  test('ThemeDataTween control test', () {
13 14 15
    final ThemeData light = new ThemeData.light();
    final ThemeData dark = new ThemeData.light();
    final ThemeDataTween tween = new ThemeDataTween(begin: light, end: dark);
16 17 18
    expect(tween.lerp(0.25), equals(ThemeData.lerp(light, dark, 0.25)));
  });

19 20 21 22 23 24 25 26 27 28 29 30
  testWidgets('PopupMenu inherits app theme', (WidgetTester tester) async {
    final Key popupMenuButtonKey = new UniqueKey();
    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(brightness: Brightness.dark),
        home: new Scaffold(
          appBar: new AppBar(
            actions: <Widget>[
              new PopupMenuButton<String>(
                key: popupMenuButtonKey,
                itemBuilder: (BuildContext context) {
                  return <PopupMenuItem<String>>[
31
                    const PopupMenuItem<String>(child: const Text('menuItem'))
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
                  ];
                }
              ),
            ]
          )
        )
      )
    );

    await tester.tap(find.byKey(popupMenuButtonKey));
    await tester.pump(const Duration(seconds: 1));

    expect(Theme.of(tester.element(find.text('menuItem'))).brightness, equals(Brightness.dark));
  });

47 48 49 50 51 52 53 54 55 56 57
  testWidgets('Fallback theme', (WidgetTester tester) async {
    BuildContext capturedContext;
    await tester.pumpWidget(
      new Builder(
        builder: (BuildContext context) {
          capturedContext = context;
          return new Container();
        }
      )
    );

58
    expect(Theme.of(capturedContext), equals(ThemeData.localize(new ThemeData.fallback(), MaterialTextGeometry.englishLike)));
59 60 61
    expect(Theme.of(capturedContext, shadowThemeOnly: true), isNull);
  });

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  testWidgets('ThemeData.localize memoizes the result', (WidgetTester tester) async {
    final ThemeData light = new ThemeData.light();
    final ThemeData dark = new ThemeData.dark();

    // Same input, same output.
    expect(
      ThemeData.localize(light, MaterialTextGeometry.englishLike),
      same(ThemeData.localize(light, MaterialTextGeometry.englishLike)),
    );

    // Different text geometry, different output.
    expect(
      ThemeData.localize(light, MaterialTextGeometry.englishLike),
      isNot(same(ThemeData.localize(light, MaterialTextGeometry.tall))),
    );

    // Different base theme, different output.
    expect(
      ThemeData.localize(light, MaterialTextGeometry.englishLike),
      isNot(same(ThemeData.localize(dark, MaterialTextGeometry.englishLike))),
    );
  });

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  testWidgets('PopupMenu inherits shadowed app theme', (WidgetTester tester) async {
    // Regression test for https://github.com/flutter/flutter/issues/5572
    final Key popupMenuButtonKey = new UniqueKey();
    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(brightness: Brightness.dark),
        home: new Theme(
          data: new ThemeData(brightness: Brightness.light),
          child: new Scaffold(
            appBar: new AppBar(
              actions: <Widget>[
                new PopupMenuButton<String>(
                  key: popupMenuButtonKey,
                  itemBuilder: (BuildContext context) {
                    return <PopupMenuItem<String>>[
100
                      const PopupMenuItem<String>(child: const Text('menuItem'))
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
                    ];
                  }
                ),
              ]
            )
          )
        )
      )
    );

    await tester.tap(find.byKey(popupMenuButtonKey));
    await tester.pump(const Duration(seconds: 1));

    expect(Theme.of(tester.element(find.text('menuItem'))).brightness, equals(Brightness.light));
  });

  testWidgets('DropdownMenu inherits shadowed app theme', (WidgetTester tester) async {
    final Key dropdownMenuButtonKey = new UniqueKey();
    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(brightness: Brightness.dark),
        home: new Theme(
          data: new ThemeData(brightness: Brightness.light),
          child: new Scaffold(
            appBar: new AppBar(
              actions: <Widget>[
                new DropdownButton<String>(
                  key: dropdownMenuButtonKey,
                  onChanged: (String newValue) { },
                  value: 'menuItem',
131
                  items: const <DropdownMenuItem<String>>[
132
                    const DropdownMenuItem<String>(
133
                      value: 'menuItem',
134
                      child: const Text('menuItem'),
135 136 137 138 139 140 141 142 143 144 145 146 147
                    ),
                  ],
                )
              ]
            )
          )
        )
      )
    );

    await tester.tap(find.byKey(dropdownMenuButtonKey));
    await tester.pump(const Duration(seconds: 1));

148
    for (Element item in tester.elementList(find.text('menuItem')))
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
      expect(Theme.of(item).brightness, equals(Brightness.light));
  });

  testWidgets('ModalBottomSheet inherits shadowed app theme', (WidgetTester tester) async {
    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(brightness: Brightness.dark),
        home: new Theme(
          data: new ThemeData(brightness: Brightness.light),
          child: new Scaffold(
            body: new Center(
              child: new Builder(
                builder: (BuildContext context) {
                  return new RaisedButton(
                    onPressed: () {
164
                      showModalBottomSheet<void>(
165
                        context: context,
166
                        builder: (BuildContext context) => const Text('bottomSheet'),
167 168
                      );
                    },
169
                    child: const Text('SHOW'),
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
                  );
                }
              )
            )
          )
        )
      )
    );

    await tester.tap(find.text('SHOW'));
    await tester.pump(const Duration(seconds: 1));
    expect(Theme.of(tester.element(find.text('bottomSheet'))).brightness, equals(Brightness.light));

    await tester.tap(find.text('bottomSheet')); // dismiss the bottom sheet
    await tester.pump(const Duration(seconds: 1));
  });

  testWidgets('Dialog inherits shadowed app theme', (WidgetTester tester) async {
    final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(brightness: Brightness.dark),
        home: new Theme(
          data: new ThemeData(brightness: Brightness.light),
          child: new Scaffold(
            key: scaffoldKey,
            body: new Center(
              child: new Builder(
                builder: (BuildContext context) {
                  return new RaisedButton(
                    onPressed: () {
201
                      showDialog<void>(
202
                        context: context,
203
                        builder: (BuildContext context) => const Text('dialog'),
204 205
                      );
                    },
206
                    child: const Text('SHOW'),
207 208 209 210 211 212 213 214 215 216 217 218 219 220
                  );
                }
              )
            )
          )
        )
      )
    );

    await tester.tap(find.text('SHOW'));
    await tester.pump(const Duration(seconds: 1));
    expect(Theme.of(tester.element(find.text('dialog'))).brightness, equals(Brightness.light));
  });

221 222 223 224 225 226 227 228 229 230 231 232
  testWidgets("Scaffold inherits theme's scaffoldBackgroundColor", (WidgetTester tester) async {
    const Color green = const Color(0xFF00FF00);

    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(scaffoldBackgroundColor: green),
        home: new Scaffold(
          body: new Center(
            child: new Builder(
              builder: (BuildContext context) {
                return new GestureDetector(
                  onTap: () {
233
                    showDialog<void>(
234
                      context: context,
235 236 237 238 239 240 241 242
                      builder: (BuildContext context) {
                        return const Scaffold(
                          body: const SizedBox(
                            width: 200.0,
                            height: 200.0,
                          ),
                        );
                      },
243 244
                    );
                  },
245
                  child: const Text('SHOW'),
246 247 248 249 250 251 252 253 254 255 256
                );
              },
            ),
          ),
        ),
      )
    );

    await tester.tap(find.text('SHOW'));
    await tester.pump(const Duration(seconds: 1));

257
    final List<Material> materials = tester.widgetList<Material>(find.byType(Material)).toList();
258 259 260 261
    expect(materials.length, equals(2));
    expect(materials[0].color, green); // app scaffold
    expect(materials[1].color, green); // dialog scaffold
  });
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

  testWidgets('IconThemes are applied', (WidgetTester tester) async {
    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(iconTheme: const IconThemeData(color: Colors.green, size: 10.0)),
        home: const Icon(Icons.computer),
      )
    );

    RenderParagraph glyphText = tester.renderObject(find.byType(RichText));

    expect(glyphText.text.style.color, Colors.green);
    expect(glyphText.text.style.fontSize, 10.0);

    await tester.pumpWidget(
      new MaterialApp(
        theme: new ThemeData(iconTheme: const IconThemeData(color: Colors.orange, size: 20.0)),
        home: const Icon(Icons.computer),
      ),
    );
    await tester.pump(const Duration(milliseconds: 100)); // Halfway through the theme transition

    glyphText = tester.renderObject(find.byType(RichText));

    expect(glyphText.text.style.color, Color.lerp(Colors.green, Colors.orange, 0.5));
    expect(glyphText.text.style.fontSize, 15.0);

    await tester.pump(const Duration(milliseconds: 100)); // Finish the transition
    glyphText = tester.renderObject(find.byType(RichText));

    expect(glyphText.text.style.color, Colors.orange);
    expect(glyphText.text.style.fontSize, 20.0);
  });
295 296

  testWidgets(
Ian Hickson's avatar
Ian Hickson committed
297
    'Same ThemeData reapplied does not trigger descendants rebuilds',
298 299 300 301
    (WidgetTester tester) async {
      testBuildCalled = 0;
      ThemeData themeData = new ThemeData(primaryColor: const Color(0xFF000000));

302 303
      Widget buildTheme() {
        return new Theme(
304 305
          data: themeData,
          child: const Test(),
306 307 308 309
        );
      }

      await tester.pumpWidget(buildTheme());
310 311 312
      expect(testBuildCalled, 1);

      // Pump the same widgets again.
313
      await tester.pumpWidget(buildTheme());
314 315 316 317 318
      // No repeated build calls to the child since it's the same theme data.
      expect(testBuildCalled, 1);

      // New instance of theme data but still the same content.
      themeData = new ThemeData(primaryColor: const Color(0xFF000000));
319
      await tester.pumpWidget(buildTheme());
320 321 322 323 324
      // Still no repeated calls.
      expect(testBuildCalled, 1);

      // Different now.
      themeData = new ThemeData(primaryColor: const Color(0xFF222222));
325
      await tester.pumpWidget(buildTheme());
326 327 328 329
      // Should call build again.
      expect(testBuildCalled, 2);
    },
  );
330 331 332 333 334 335 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

  testWidgets('Text geometry set in Theme has higher precedence than that of Localizations', (WidgetTester tester) async {
    const double _kMagicFontSize = 4321.0;
    final ThemeData fallback = new ThemeData.fallback();
    final ThemeData customTheme = fallback.copyWith(
      primaryTextTheme: fallback.primaryTextTheme.copyWith(
        body1: fallback.primaryTextTheme.body1.copyWith(
          fontSize: _kMagicFontSize,
        )
      ),
    );
    expect(customTheme.primaryTextTheme.body1.fontSize, _kMagicFontSize);

    double actualFontSize;
    await tester.pumpWidget(new Directionality(
      textDirection: TextDirection.ltr,
      child: new Theme(
        data: customTheme,
        child: new Builder(builder: (BuildContext context) {
          final ThemeData theme = Theme.of(context);
          actualFontSize = theme.primaryTextTheme.body1.fontSize;
          return new Text(
            'A',
            style: theme.primaryTextTheme.body1,
          );
        }),
      ),
    ));

    expect(actualFontSize, _kMagicFontSize);
  });
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 403 404 405 406 407 408

  testWidgets('Default Theme provides all basic TextStyle properties', (WidgetTester tester) async {
    ThemeData theme;
    await tester.pumpWidget(new Directionality(
      textDirection: TextDirection.ltr,
      child: new Builder(
        builder: (BuildContext context) {
          theme = Theme.of(context);
          return const Text('A');
        },
      ),
    ));

    List<TextStyle> extractStyles(TextTheme textTheme) {
      return <TextStyle>[
        textTheme.display4,
        textTheme.display3,
        textTheme.display2,
        textTheme.display1,
        textTheme.headline,
        textTheme.title,
        textTheme.subhead,
        textTheme.body2,
        textTheme.body1,
        textTheme.caption,
        textTheme.button,
      ];
    }

    for (TextTheme textTheme in <TextTheme>[theme.textTheme, theme.primaryTextTheme, theme.accentTextTheme]) {
      for (TextStyle style in extractStyles(textTheme).map((TextStyle style) => new _TextStyleProxy(style))) {
        expect(style.inherit, false);
        expect(style.color, isNotNull);
        expect(style.fontFamily, isNotNull);
        expect(style.fontSize, isNotNull);
        expect(style.fontWeight, isNotNull);
        expect(style.fontStyle, null);
        expect(style.letterSpacing, null);
        expect(style.wordSpacing, null);
        expect(style.textBaseline, isNotNull);
        expect(style.height, null);
        expect(style.decoration, TextDecoration.none);
        expect(style.decorationColor, null);
        expect(style.decorationStyle, null);
        expect(style.debugLabel, isNotNull);
      }
    }

409
    expect(theme.textTheme.display4.debugLabel, '(englishLike display4).merge(blackMountainView display4)');
410
  });
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
}

int testBuildCalled;
class Test extends StatefulWidget {
  const Test();

  @override
  _TestState createState() => new _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    testBuildCalled += 1;
    return new Container(
      decoration: new BoxDecoration(
        color: Theme.of(context).primaryColor,
      ),
    );
  }
431
}
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

/// This class exists only to make sure that we test all the properties of the
/// [TextStyle] class. If a property is added/removed/renamed, the analyzer will
/// complain that this class has incorrect overrides.
class _TextStyleProxy implements TextStyle {
  _TextStyleProxy(this._delegate);

  final TextStyle _delegate;

  // Do make sure that all the properties correctly forward to the _delegate.
  @override Color get color => _delegate.color;
  @override String get debugLabel => _delegate.debugLabel;
  @override TextDecoration get decoration => _delegate.decoration;
  @override Color get decorationColor => _delegate.decorationColor;
  @override TextDecorationStyle get decorationStyle => _delegate.decorationStyle;
  @override String get fontFamily => _delegate.fontFamily;
  @override double get fontSize => _delegate.fontSize;
  @override FontStyle get fontStyle => _delegate.fontStyle;
  @override FontWeight get fontWeight => _delegate.fontWeight;
  @override double get height => _delegate.height;
452
  @override ui.Locale get locale => _delegate.locale;
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
  @override bool get inherit => _delegate.inherit;
  @override double get letterSpacing => _delegate.letterSpacing;
  @override TextBaseline get textBaseline => _delegate.textBaseline;
  @override double get wordSpacing => _delegate.wordSpacing;

  @override
  DiagnosticsNode toDiagnosticsNode({String name, DiagnosticsTreeStyle style}) {
    throw new UnimplementedError();
  }

  @override
  String toStringShort() {
    throw new UnimplementedError();
  }

  @override
  TextStyle apply({Color color, TextDecoration decoration, Color decorationColor, TextDecorationStyle decorationStyle, String fontFamily, double fontSizeFactor: 1.0, double fontSizeDelta: 0.0, int fontWeightDelta: 0, double letterSpacingFactor: 1.0, double letterSpacingDelta: 0.0, double wordSpacingFactor: 1.0, double wordSpacingDelta: 0.0, double heightFactor: 1.0, double heightDelta: 0.0}) {
    throw new UnimplementedError();
  }

  @override
  RenderComparison compareTo(TextStyle other) {
    throw new UnimplementedError();
  }

  @override
479
  TextStyle copyWith({Color color, String fontFamily, double fontSize, FontWeight fontWeight, FontStyle fontStyle, double letterSpacing, double wordSpacing, TextBaseline textBaseline, double height, ui.Locale locale, TextDecoration decoration, Color decorationColor, TextDecorationStyle decorationStyle, String debugLabel}) {
480 481 482 483 484 485 486 487 488
    throw new UnimplementedError();
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties, {String prefix: ''}) {
    throw new UnimplementedError();
  }

  @override
489
  ui.ParagraphStyle getParagraphStyle({TextAlign textAlign, TextDirection textDirection, double textScaleFactor: 1.0, String ellipsis, int maxLines, ui.Locale locale}) {
490 491 492 493 494 495 496 497 498 499 500 501 502
    throw new UnimplementedError();
  }

  @override
  ui.TextStyle getTextStyle({double textScaleFactor: 1.0}) {
    throw new UnimplementedError();
  }

  @override
  TextStyle merge(TextStyle other) {
    throw new UnimplementedError();
  }
}