search_test.dart 30.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/material.dart';
7
import 'package:flutter/services.dart';
8 9
import 'package:flutter_test/flutter_test.dart';

10 11
import '../widgets/semantics_tester.dart';

12
class MockClipboard {
13
  dynamic _clipboardData = <String, dynamic>{
14 15 16 17 18 19 20 21 22 23 24 25 26 27
    'text': null,
  };

  Future<dynamic> handleMethodCall(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'Clipboard.getData':
        return _clipboardData;
      case 'Clipboard.setData':
        _clipboardData = methodCall.arguments;
        break;
    }
  }
}

28
void main() {
29 30 31 32
  TestWidgetsFlutterBinding.ensureInitialized();
  final MockClipboard mockClipboard = MockClipboard();

  setUp(() async {
33
    // Fill the clipboard so that the Paste option is available in the text
34 35 36 37 38 39 40 41 42
    // selection menu.
    SystemChannels.platform.setMockMethodCallHandler(mockClipboard.handleMethodCall);
    await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
  });

  tearDown(() {
    SystemChannels.platform.setMockMethodCallHandler(null);
  });

43
  testWidgets('Can open and close search', (WidgetTester tester) async {
44
    final _TestSearchDelegate delegate = _TestSearchDelegate();
45 46
    final List<String> selectedResults = <String>[];

47
    await tester.pumpWidget(TestHomePage(
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
      delegate: delegate,
      results: selectedResults,
    ));

    // We are on the homepage
    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);

    // Open search
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(selectedResults, hasLength(0));

    final TextField textField = tester.widget(find.byType(TextField));
67
    expect(textField.focusNode!.hasFocus, isTrue);
68 69 70 71 72 73 74 75 76 77 78

    // Close search
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(selectedResults, <String>['Result']);
  });

79 80 81
  testWidgets('Can close search with system back button to return null', (WidgetTester tester) async {
    // regression test for https://github.com/flutter/flutter/issues/18145

82
    final _TestSearchDelegate delegate = _TestSearchDelegate();
83
    final List<String?> selectedResults = <String?>[];
84

85
    await tester.pumpWidget(TestHomePage(
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      delegate: delegate,
      results: selectedResults,
    ));

    // We are on the homepage
    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);

    // Open search
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
102
    expect(find.text('Bottom'), findsOneWidget);
103 104 105

    // Simulate system back button
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
106
    await ServicesBinding.instance!.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
107 108
    await tester.pumpAndSettle();

109
    expect(selectedResults, <String?>[null]);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    // We are on the homepage again
    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);

    // Open search again
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
  });

125
  testWidgets('Hint text color overridden', (WidgetTester tester) async {
126 127
    const String searchHintText = 'Enter search terms';
    final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHintText);
128 129 130 131 132 133 134

    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

135 136
    final Text hintText = tester.widget(find.text(searchHintText));
    expect(hintText.style!.color, _TestSearchDelegate.hintTextColor);
137 138
  });

139
  testWidgets('Requests suggestions', (WidgetTester tester) async {
140
    final _TestSearchDelegate delegate = _TestSearchDelegate();
141

142
    await tester.pumpWidget(TestHomePage(
143 144 145 146 147 148
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');
149 150
    expect(delegate.queriesForSuggestions.last, '');
    expect(delegate.queriesForResults, hasLength(0));
151 152

    // Type W o w into search field
153
    delegate.queriesForSuggestions.clear();
154 155 156 157 158 159 160 161 162 163
    await tester.enterText(find.byType(TextField), 'W');
    await tester.pumpAndSettle();
    expect(delegate.query, 'W');
    await tester.enterText(find.byType(TextField), 'Wo');
    await tester.pumpAndSettle();
    expect(delegate.query, 'Wo');
    await tester.enterText(find.byType(TextField), 'Wow');
    await tester.pumpAndSettle();
    expect(delegate.query, 'Wow');

164 165
    expect(delegate.queriesForSuggestions, <String>['W', 'Wo', 'Wow']);
    expect(delegate.queriesForResults, hasLength(0));
166 167 168
  });

  testWidgets('Shows Results and closes search', (WidgetTester tester) async {
169
    final _TestSearchDelegate delegate = _TestSearchDelegate();
170 171
    final List<String> selectedResults = <String>[];

172
    await tester.pumpWidget(TestHomePage(
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
      delegate: delegate,
      results: selectedResults,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();
    await tester.enterText(find.byType(TextField), 'Wow');
    await tester.pumpAndSettle();
    await tester.tap(find.text('Suggestions'));
    await tester.pumpAndSettle();

    // We are on the results page for Wow
    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsOneWidget);

    final TextField textField = tester.widget(find.byType(TextField));
190
    expect(textField.focusNode!.hasFocus, isFalse);
191
    expect(delegate.queriesForResults, <String>['Wow']);
192 193 194 195 196 197 198 199 200 201 202 203

    // Close search
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsNothing);
    expect(selectedResults, <String>['Result']);
  });

204
  testWidgets('Can switch between results and suggestions', (WidgetTester tester) async {
205
    final _TestSearchDelegate delegate = _TestSearchDelegate();
206

207
    await tester.pumpWidget(TestHomePage(
208 209 210
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
211
    await tester.pumpAndSettle();
212 213 214 215 216 217

    // Showing suggestions
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Results'), findsNothing);

    // Typing query Wow
218
    delegate.queriesForSuggestions.clear();
219
    await tester.enterText(find.byType(TextField), 'Wow');
220
    await tester.pumpAndSettle();
221 222

    expect(delegate.query, 'Wow');
223 224
    expect(delegate.queriesForSuggestions, <String>['Wow']);
    expect(delegate.queriesForResults, hasLength(0));
225 226

    await tester.tap(find.text('Suggestions'));
227
    await tester.pumpAndSettle();
228 229 230 231 232 233

    // Showing Results
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsOneWidget);

    expect(delegate.query, 'Wow');
234 235
    expect(delegate.queriesForSuggestions, <String>['Wow']);
    expect(delegate.queriesForResults, <String>['Wow']);
236 237

    TextField textField = tester.widget(find.byType(TextField));
238
    expect(textField.focusNode!.hasFocus, isFalse);
239

240
    // Tapping search field to go back to suggestions
241
    await tester.tap(find.byType(TextField));
242
    await tester.pumpAndSettle();
243 244

    textField = tester.widget(find.byType(TextField));
245
    expect(textField.focusNode!.hasFocus, isTrue);
246 247 248

    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Results'), findsNothing);
249 250
    expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow']);
    expect(delegate.queriesForResults, <String>['Wow']);
251 252

    await tester.enterText(find.byType(TextField), 'Foo');
253
    await tester.pumpAndSettle();
254 255

    expect(delegate.query, 'Foo');
256 257
    expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow', 'Foo']);
    expect(delegate.queriesForResults, <String>['Wow']);
258 259 260

    // Go to results again
    await tester.tap(find.text('Suggestions'));
261
    await tester.pumpAndSettle();
262 263 264 265 266

    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsOneWidget);

    expect(delegate.query, 'Foo');
267 268
    expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow', 'Foo']);
    expect(delegate.queriesForResults, <String>['Wow', 'Foo']);
269 270

    textField = tester.widget(find.byType(TextField));
271
    expect(textField.focusNode!.hasFocus, isFalse);
272 273
  });

274
  testWidgets('Fresh search always starts with empty query', (WidgetTester tester) async {
275
    final _TestSearchDelegate delegate = _TestSearchDelegate();
276

277
    await tester.pumpWidget(TestHomePage(
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');

    delegate.query = 'Foo';
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');
  });

  testWidgets('Initial queries are honored', (WidgetTester tester) async {
295
    final _TestSearchDelegate delegate = _TestSearchDelegate();
296 297 298

    expect(delegate.query, '');

299
    await tester.pumpWidget(TestHomePage(
300 301 302 303 304 305 306 307 308 309 310
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: 'Foo',
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, 'Foo');
  });

  testWidgets('Initial query null re-used previous query', (WidgetTester tester) async {
311
    final _TestSearchDelegate delegate = _TestSearchDelegate();
312 313 314

    delegate.query = 'Foo';

315
    await tester.pumpWidget(TestHomePage(
316 317 318 319 320 321 322 323 324 325 326
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: null,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, 'Foo');
  });

  testWidgets('Changing query shows up in search field', (WidgetTester tester) async {
327
    final _TestSearchDelegate delegate = _TestSearchDelegate();
328

329
    await tester.pumpWidget(TestHomePage(
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: null,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    delegate.query = 'Foo';

    expect(find.text('Foo'), findsOneWidget);
    expect(find.text('Bar'), findsNothing);

    delegate.query = 'Bar';

    expect(find.text('Foo'), findsNothing);
    expect(find.text('Bar'), findsOneWidget);
  });

  testWidgets('transitionAnimation runs while search fades in/out', (WidgetTester tester) async {
349
    final _TestSearchDelegate delegate = _TestSearchDelegate();
350

351
    await tester.pumpWidget(TestHomePage(
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
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: null,
    ));

    // runs while search fades in
    expect(delegate.transitionAnimation.status, AnimationStatus.dismissed);
    await tester.tap(find.byTooltip('Search'));
    expect(delegate.transitionAnimation.status, AnimationStatus.forward);
    await tester.pumpAndSettle();
    expect(delegate.transitionAnimation.status, AnimationStatus.completed);

    // does not run while switching to results
    await tester.tap(find.text('Suggestions'));
    expect(delegate.transitionAnimation.status, AnimationStatus.completed);
    await tester.pumpAndSettle();
    expect(delegate.transitionAnimation.status, AnimationStatus.completed);

    // runs while search fades out
    await tester.tap(find.byTooltip('Back'));
    expect(delegate.transitionAnimation.status, AnimationStatus.reverse);
    await tester.pumpAndSettle();
    expect(delegate.transitionAnimation.status, AnimationStatus.dismissed);
  });

  testWidgets('Closing nested search returns to search', (WidgetTester tester) async {
378
    final List<String?> nestedSearchResults = <String?>[];
379
    final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
380 381 382 383 384
      suggestions: 'Nested Suggestions',
      result: 'Nested Result',
    );

    final List<String> selectedResults = <String>[];
385
    final _TestSearchDelegate delegate = _TestSearchDelegate(
386
      actions: <Widget>[
387
        Builder(
388
          builder: (BuildContext context) {
389
            return IconButton(
390 391 392
              tooltip: 'Nested Search',
              icon: const Icon(Icons.search),
              onPressed: () async {
393
                final String? result = await showSearch(
394 395 396 397 398 399 400
                  context: context,
                  delegate: nestedSearchDelegate,
                );
                nestedSearchResults.add(result);
              },
            );
          },
401
        ),
402 403 404
      ],
    );

405
    await tester.pumpWidget(TestHomePage(
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
      delegate: delegate,
      results: selectedResults,
    ));
    expect(find.text('HomeBody'), findsOneWidget);
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Nested Suggestions'), findsNothing);

    await tester.tap(find.byTooltip('Nested Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsOneWidget);

    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();
    expect(nestedSearchResults, <String>['Nested Result']);

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Nested Suggestions'), findsNothing);

    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsNothing);
    expect(selectedResults, <String>['Result']);
  });

  testWidgets('Closing search with nested search shown goes back to underlying route', (WidgetTester tester) async {
442 443
    late _TestSearchDelegate delegate;
    final List<String?> nestedSearchResults = <String?>[];
444
    final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
445 446 447
      suggestions: 'Nested Suggestions',
      result: 'Nested Result',
      actions: <Widget>[
448
        Builder(
449
          builder: (BuildContext context) {
450
            return IconButton(
451 452 453 454 455 456 457
              tooltip: 'Close Search',
              icon: const Icon(Icons.close),
              onPressed: () async {
                delegate.close(context, 'Result Foo');
              },
            );
          },
458
        ),
459 460 461 462
      ],
    );

    final List<String> selectedResults = <String>[];
463
    delegate = _TestSearchDelegate(
464
      actions: <Widget>[
465
        Builder(
466
          builder: (BuildContext context) {
467
            return IconButton(
468 469 470
              tooltip: 'Nested Search',
              icon: const Icon(Icons.search),
              onPressed: () async {
471
                final String? result = await showSearch(
472 473 474 475 476 477 478
                  context: context,
                  delegate: nestedSearchDelegate,
                );
                nestedSearchResults.add(result);
              },
            );
          },
479
        ),
480 481 482
      ],
    );

483
    await tester.pumpWidget(TestHomePage(
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
      delegate: delegate,
      results: selectedResults,
    ));

    expect(find.text('HomeBody'), findsOneWidget);
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Nested Suggestions'), findsNothing);

    await tester.tap(find.byTooltip('Nested Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsOneWidget);

    await tester.tap(find.byTooltip('Close Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsNothing);
509
    expect(nestedSearchResults, <String?>[null]);
510 511
    expect(selectedResults, <String>['Result Foo']);
  });
512

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
  testWidgets('Custom searchFieldLabel value', (WidgetTester tester) async {
    const String searchHint = 'custom search hint';
    final String defaultSearchHint = const DefaultMaterialLocalizations().searchFieldLabel;

    final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHint);

    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text(searchHint), findsOneWidget);
    expect(find.text(defaultSearchHint), findsNothing);
  });

  testWidgets('Default searchFieldLabel is used when it is set to null', (WidgetTester tester) async {
    final String searchHint = const DefaultMaterialLocalizations().searchFieldLabel;

    final _TestSearchDelegate delegate = _TestSearchDelegate();

    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text(searchHint), findsOneWidget);
  });

543
  testWidgets('Custom searchFieldStyle value', (WidgetTester tester) async {
544 545
    const String searchHintText = 'Enter search terms';
    const TextStyle searchFieldStyle = TextStyle(color: Colors.red, fontSize: 3);
546

547
    final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHintText, searchFieldStyle: searchFieldStyle);
548

549
    await tester.pumpWidget(TestHomePage(delegate: delegate));
550 551 552
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

553 554 555
    final Text hintText = tester.widget(find.text(searchHintText));
    expect(hintText.style?.color, delegate.searchFieldStyle?.color);
    expect(hintText.style?.fontSize, delegate.searchFieldStyle?.fontSize);
556 557
  });

558
  testWidgets('keyboard show search button by default', (WidgetTester tester) async {
559
    final _TestSearchDelegate delegate = _TestSearchDelegate();
560

561
    await tester.pumpWidget(TestHomePage(
562 563 564 565 566 567 568
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    await tester.showKeyboard(find.byType(TextField));

569
    expect(tester.testTextInput.setClientArgs!['inputAction'], TextInputAction.search.toString());
570
  });
571

572 573 574 575 576 577 578 579 580
  testWidgets('Custom textInputAction results in keyboard with corresponding button', (WidgetTester tester) async {
    final _TestSearchDelegate delegate = _TestSearchDelegate(textInputAction: TextInputAction.done);

    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();
    await tester.showKeyboard(find.byType(TextField));
581
    expect(tester.testTextInput.setClientArgs!['inputAction'], TextInputAction.done.toString());
582 583
  });

584
  group('contributes semantics', () {
585
    TestSemantics buildExpected({ required String routeName }) {
586
      return TestSemantics.root(
587
        children: <TestSemantics>[
588
          TestSemantics(
589 590 591
            id: 1,
            textDirection: TextDirection.ltr,
            children: <TestSemantics>[
592
              TestSemantics(
593
                id: 2,
594
                children: <TestSemantics>[
595
                  TestSemantics(
596 597 598 599 600 601 602
                    id: 7,
                    flags: <SemanticsFlag>[
                      SemanticsFlag.scopesRoute,
                      SemanticsFlag.namesRoute,
                    ],
                    label: routeName,
                    textDirection: TextDirection.ltr,
603
                    children: <TestSemantics>[
604
                      TestSemantics(
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
                        id: 9,
                        children: <TestSemantics>[
                          TestSemantics(
                            id: 10,
                            flags: <SemanticsFlag>[
                              SemanticsFlag.hasEnabledState,
                              SemanticsFlag.isButton,
                              SemanticsFlag.isEnabled,
                              SemanticsFlag.isFocusable,
                            ],
                            actions: <SemanticsAction>[SemanticsAction.tap],
                            label: 'Back',
                            textDirection: TextDirection.ltr,
                          ),
                          TestSemantics(
                            id: 11,
                            flags: <SemanticsFlag>[
                              SemanticsFlag.isTextField,
                              SemanticsFlag.isFocused,
                              SemanticsFlag.isHeader,
                              if (debugDefaultTargetPlatformOverride != TargetPlatform.iOS &&
                                debugDefaultTargetPlatformOverride != TargetPlatform.macOS) SemanticsFlag.namesRoute,
                            ],
                            actions: <SemanticsAction>[
629 630
                              if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS)
                                SemanticsAction.didGainAccessibilityFocus,
631 632
                              SemanticsAction.tap,
                              SemanticsAction.setSelection,
633
                              SemanticsAction.setText,
634 635 636 637 638 639
                              SemanticsAction.paste,
                            ],
                            label: 'Search',
                            textDirection: TextDirection.ltr,
                            textSelection: const TextSelection(baseOffset: 0, extentOffset: 0),
                          ),
640 641 642 643 644
                          TestSemantics(
                            id: 14,
                            label: 'Bottom',
                            textDirection: TextDirection.ltr,
                          ),
645 646 647 648
                        ],
                      ),
                      TestSemantics(
                        id: 8,
649 650
                        flags: <SemanticsFlag>[
                          SemanticsFlag.hasEnabledState,
651
                          SemanticsFlag.isButton,
652
                          SemanticsFlag.isEnabled,
653
                          SemanticsFlag.isFocusable,
654 655
                        ],
                        actions: <SemanticsAction>[SemanticsAction.tap],
656
                        label: 'Suggestions',
657 658 659 660 661 662 663 664 665 666 667 668 669
                        textDirection: TextDirection.ltr,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ],
      );
    }

    testWidgets('includes routeName on Android', (WidgetTester tester) async {
670 671 672
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate();
      await tester.pumpWidget(TestHomePage(
673 674 675 676 677 678 679 680 681 682 683 684
        delegate: delegate,
      ));

      await tester.tap(find.byTooltip('Search'));
      await tester.pumpAndSettle();

      expect(semantics, hasSemantics(buildExpected(routeName: 'Search'),
          ignoreId: true, ignoreRect: true, ignoreTransform: true));

      semantics.dispose();
    });

Dan Field's avatar
Dan Field committed
685
    testWidgets('does not include routeName', (WidgetTester tester) async {
686 687 688
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate();
      await tester.pumpWidget(TestHomePage(
689 690 691 692 693 694 695 696 697 698
        delegate: delegate,
      ));

      await tester.tap(find.byTooltip('Search'));
      await tester.pumpAndSettle();

      expect(semantics, hasSemantics(buildExpected(routeName: ''),
          ignoreId: true, ignoreRect: true, ignoreTransform: true));

      semantics.dispose();
Dan Field's avatar
Dan Field committed
699
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
700
  });
701

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
  testWidgets('Custom searchFieldDecorationTheme value',
      (WidgetTester tester) async {
    const InputDecorationTheme searchFieldDecorationTheme = InputDecorationTheme(
      hintStyle: TextStyle(color: _TestSearchDelegate.hintTextColor),
    );
    final _TestSearchDelegate delegate = _TestSearchDelegate(
      searchFieldDecorationTheme: searchFieldDecorationTheme,
    );

    await tester.pumpWidget(TestHomePage(delegate: delegate));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    final ThemeData textFieldTheme = Theme.of(tester.element(find.byType(TextField)));
    expect(textFieldTheme.inputDecorationTheme, searchFieldDecorationTheme);
  });

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  // Regression test for: https://github.com/flutter/flutter/issues/66781
  testWidgets('text in search bar contrasts background (light mode)', (WidgetTester tester) async {
      final ThemeData themeData = ThemeData.light();
      final _TestSearchDelegate delegate = _TestSearchDelegate(
        defaultAppBarTheme: true,
      );
      const String query = 'search query';
      await tester.pumpWidget(TestHomePage(
        delegate: delegate,
        passInInitialQuery: true,
        initialQuery: query,
        themeData: themeData,
      ));

      await tester.tap(find.byTooltip('Search'));
      await tester.pumpAndSettle();

736 737 738 739 740
      final Material appBarBackground = tester.widget<Material>(find.descendant(
        of: find.byType(AppBar),
        matching: find.byType(Material),
      ));
      expect(appBarBackground.color, Colors.white);
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

      final TextField textField = tester.widget<TextField>(find.byType(TextField));
      expect(textField.style!.color, themeData.textTheme.bodyText1!.color);
      expect(textField.style!.color, isNot(equals(Colors.white)));
  });

  // Regression test for: https://github.com/flutter/flutter/issues/66781
  testWidgets('text in search bar contrasts background (dark mode)', (WidgetTester tester) async {
      final ThemeData themeData = ThemeData.dark();
      final _TestSearchDelegate delegate = _TestSearchDelegate(
        defaultAppBarTheme: true,
      );
      const String query = 'search query';
      await tester.pumpWidget(TestHomePage(
        delegate: delegate,
        passInInitialQuery: true,
        initialQuery: query,
        themeData: themeData,
      ));

      await tester.tap(find.byTooltip('Search'));
      await tester.pumpAndSettle();

764 765 766 767 768
      final Material appBarBackground = tester.widget<Material>(find.descendant(
        of: find.byType(AppBar),
        matching: find.byType(Material),
      ));
      expect(appBarBackground.color, themeData.primaryColor);
769 770 771 772 773

      final TextField textField = tester.widget<TextField>(find.byType(TextField));
      expect(textField.style!.color, themeData.textTheme.bodyText1!.color);
      expect(textField.style!.color, isNot(equals(themeData.primaryColor)));
  });
774 775 776 777
}

class TestHomePage extends StatelessWidget {
  const TestHomePage({
778
    Key? key,
779
    this.results,
780
    required this.delegate,
781
    this.passInInitialQuery = false,
782
    this.initialQuery,
783
    this.themeData,
784
  }) : super(key: key);
785

786
  final List<String?>? results;
787 788
  final SearchDelegate<String> delegate;
  final bool passInInitialQuery;
789
  final ThemeData? themeData;
790
  final String? initialQuery;
791 792 793

  @override
  Widget build(BuildContext context) {
794
    return MaterialApp(
795
      theme: themeData,
796
      home: Builder(builder: (BuildContext context) {
797 798
        return Scaffold(
          appBar: AppBar(
799 800
            title: const Text('HomeTitle'),
            actions: <Widget>[
801
              IconButton(
802 803 804
                tooltip: 'Search',
                icon: const Icon(Icons.search),
                onPressed: () async {
805
                  String? selectedResult;
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
                  if (passInInitialQuery) {
                    selectedResult = await showSearch<String>(
                      context: context,
                      delegate: delegate,
                      query: initialQuery,
                    );
                  } else {
                    selectedResult = await showSearch<String>(
                      context: context,
                      delegate: delegate,
                    );
                  }
                  results?.add(selectedResult);
                },
              ),
            ],
          ),
          body: const Text('HomeBody'),
        );
      }),
    );
  }
}

class _TestSearchDelegate extends SearchDelegate<String> {
  _TestSearchDelegate({
832 833 834
    this.suggestions = 'Suggestions',
    this.result = 'Result',
    this.actions = const <Widget>[],
835
    this.defaultAppBarTheme = false,
836
    InputDecorationTheme? searchFieldDecorationTheme,
837 838
    TextStyle? searchFieldStyle,
    String? searchHint,
839
    TextInputAction textInputAction = TextInputAction.search,
840 841 842 843 844 845
  }) : super(
          searchFieldLabel: searchHint,
          textInputAction: textInputAction,
          searchFieldStyle: searchFieldStyle,
          searchFieldDecorationTheme: searchFieldDecorationTheme,
        );
846

847
  final bool defaultAppBarTheme;
848 849 850
  final String suggestions;
  final String result;
  final List<Widget> actions;
851
  static const Color hintTextColor = Colors.green;
852 853 854

  @override
  ThemeData appBarTheme(BuildContext context) {
855 856 857
    if (defaultAppBarTheme) {
      return super.appBarTheme(context);
    }
858
    final ThemeData theme = Theme.of(context);
859
    return theme.copyWith(
860 861 862 863 864 865 866
      inputDecorationTheme: searchFieldDecorationTheme ??
          InputDecorationTheme(
            hintStyle: searchFieldStyle ??
                const TextStyle(
                  color: hintTextColor,
                ),
          ),
867 868
    );
  }
869 870 871

  @override
  Widget buildLeading(BuildContext context) {
872
    return IconButton(
873 874 875 876 877 878 879 880
      tooltip: 'Back',
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, result);
      },
    );
  }

881 882
  final List<String> queriesForSuggestions = <String>[];
  final List<String> queriesForResults = <String>[];
883 884 885

  @override
  Widget buildSuggestions(BuildContext context) {
886
    queriesForSuggestions.add(query);
887
    return MaterialButton(
888 889 890
      onPressed: () {
        showResults(context);
      },
891
      child: Text(suggestions),
892 893 894 895 896
    );
  }

  @override
  Widget buildResults(BuildContext context) {
897
    queriesForResults.add(query);
898 899 900 901 902 903 904
    return const Text('Results');
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return actions;
  }
905 906 907 908 909 910 911 912

  @override
  PreferredSizeWidget buildBottom(BuildContext context) {
    return const PreferredSize(
      preferredSize: Size.fromHeight(56.0),
      child: Text('Bottom'),
    );
  }
913
}