search_test.dart 33.3 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
    // selection menu.
35
    SystemChannels.platform.setMockMethodCallHandler(mockClipboard.handleMethodCall);
36 37 38 39
    await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
  });

  tearDown(() {
40
    SystemChannels.platform.setMockMethodCallHandler(null);
41 42
  });

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
        delegate: delegate,
      ));

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

679 680 681 682 683 684
      expect(semantics, hasSemantics(
        buildExpected(routeName: 'Search'),
        ignoreId: true,
        ignoreRect: true,
        ignoreTransform: true,
      ));
685 686 687 688

      semantics.dispose();
    });

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

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

699 700 701 702 703 704
      expect(semantics, hasSemantics(
        buildExpected(routeName: ''),
        ignoreId: true,
        ignoreRect: true,
        ignoreTransform: true,
      ));
705 706

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

710
  testWidgets('Custom searchFieldDecorationTheme value', (WidgetTester tester) async {
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    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);
  });

726 727
  // Regression test for: https://github.com/flutter/flutter/issues/66781
  testWidgets('text in search bar contrasts background (light mode)', (WidgetTester tester) async {
728 729 730 731 732 733 734 735 736 737 738
    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,
    ));
739

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

743 744 745 746 747
    final Material appBarBackground = tester.widget<Material>(find.descendant(
      of: find.byType(AppBar),
      matching: find.byType(Material),
    ));
    expect(appBarBackground.color, Colors.white);
748

749 750 751
    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)));
752 753 754 755
  });

  // Regression test for: https://github.com/flutter/flutter/issues/66781
  testWidgets('text in search bar contrasts background (dark mode)', (WidgetTester tester) async {
756 757 758 759 760 761 762 763 764 765 766
    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,
    ));
767

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

771 772 773 774 775
    final Material appBarBackground = tester.widget<Material>(find.descendant(
      of: find.byType(AppBar),
      matching: find.byType(Material),
    ));
    expect(appBarBackground.color, themeData.primaryColor);
776

777 778 779
    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)));
780
  });
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822

  // Regression test for: https://github.com/flutter/flutter/issues/78144
  testWidgets('`Leading` and `Actions` nullable test', (WidgetTester tester) async {
    // The search delegate page is displayed with no issues
    // even with a null return values for [buildLeading] and [buildActions].
    final _TestEmptySearchDelegate delegate = _TestEmptySearchDelegate(
      result: 'Result',
      suggestions: 'Suggestions',
    );
    final List<String> selectedResults = <String>[];

    await tester.pumpWidget(TestHomePage(
      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 the search page.
    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));
    expect(textField.focusNode!.hasFocus, isTrue);

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

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

class TestHomePage extends StatelessWidget {
  const TestHomePage({
827
    Key? key,
828
    this.results,
829
    required this.delegate,
830
    this.passInInitialQuery = false,
831
    this.initialQuery,
832
    this.themeData,
833
  }) : super(key: key);
834

835
  final List<String?>? results;
836 837
  final SearchDelegate<String> delegate;
  final bool passInInitialQuery;
838
  final ThemeData? themeData;
839
  final String? initialQuery;
840 841 842

  @override
  Widget build(BuildContext context) {
843
    return MaterialApp(
844
      theme: themeData,
845
      home: Builder(builder: (BuildContext context) {
846 847
        return Scaffold(
          appBar: AppBar(
848 849
            title: const Text('HomeTitle'),
            actions: <Widget>[
850
              IconButton(
851 852 853
                tooltip: 'Search',
                icon: const Icon(Icons.search),
                onPressed: () async {
854
                  String? selectedResult;
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
                  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({
881 882 883
    this.suggestions = 'Suggestions',
    this.result = 'Result',
    this.actions = const <Widget>[],
884
    this.defaultAppBarTheme = false,
885
    InputDecorationTheme? searchFieldDecorationTheme,
886 887
    TextStyle? searchFieldStyle,
    String? searchHint,
888
    TextInputAction textInputAction = TextInputAction.search,
889 890 891 892 893 894
  }) : super(
          searchFieldLabel: searchHint,
          textInputAction: textInputAction,
          searchFieldStyle: searchFieldStyle,
          searchFieldDecorationTheme: searchFieldDecorationTheme,
        );
895

896
  final bool defaultAppBarTheme;
897 898 899
  final String suggestions;
  final String result;
  final List<Widget> actions;
900
  static const Color hintTextColor = Colors.green;
901 902 903

  @override
  ThemeData appBarTheme(BuildContext context) {
904 905 906
    if (defaultAppBarTheme) {
      return super.appBarTheme(context);
    }
907
    final ThemeData theme = Theme.of(context);
908
    return theme.copyWith(
909 910 911 912 913 914 915
      inputDecorationTheme: searchFieldDecorationTheme ??
          InputDecorationTheme(
            hintStyle: searchFieldStyle ??
                const TextStyle(
                  color: hintTextColor,
                ),
          ),
916 917
    );
  }
918 919 920

  @override
  Widget buildLeading(BuildContext context) {
921
    return IconButton(
922 923 924 925 926 927 928 929
      tooltip: 'Back',
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, result);
      },
    );
  }

930 931
  final List<String> queriesForSuggestions = <String>[];
  final List<String> queriesForResults = <String>[];
932 933 934

  @override
  Widget buildSuggestions(BuildContext context) {
935
    queriesForSuggestions.add(query);
936
    return MaterialButton(
937 938 939
      onPressed: () {
        showResults(context);
      },
940
      child: Text(suggestions),
941 942 943 944 945
    );
  }

  @override
  Widget buildResults(BuildContext context) {
946
    queriesForResults.add(query);
947 948 949 950 951 952 953
    return const Text('Results');
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return actions;
  }
954 955 956 957 958 959 960 961

  @override
  PreferredSizeWidget buildBottom(BuildContext context) {
    return const PreferredSize(
      preferredSize: Size.fromHeight(56.0),
      child: Text('Bottom'),
    );
  }
962
}
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007

class _TestEmptySearchDelegate extends SearchDelegate<String> {
  _TestEmptySearchDelegate({
    this.suggestions = 'Suggestions',
    this.result = 'Result',
  }) : super();

  final String suggestions;
  final String result;

  @override
  Widget? buildLeading(BuildContext context) => null;

  @override
  List<Widget>? buildActions(BuildContext context) => null;

  @override
  Widget buildSuggestions(BuildContext context) {
    return MaterialButton(
      onPressed: () {
        showResults(context);
      },
      child: Text(suggestions),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return const Text('Results');
  }

  @override
  PreferredSizeWidget buildBottom(BuildContext context) {
    return PreferredSize(
      preferredSize: const Size.fromHeight(56.0),
      child: IconButton(
        tooltip: 'Close',
        icon: const Icon(Icons.arrow_back),
        onPressed: () {
          close(context, result);
        },
      ),
    );
  }
}