search_test.dart 44.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
import 'package:flutter_test/flutter_test.dart';
9
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
10

11
import '../widgets/clipboard_utils.dart';
12 13
import '../widgets/semantics_tester.dart';

14
void main() {
15 16 17 18
  TestWidgetsFlutterBinding.ensureInitialized();
  final MockClipboard mockClipboard = MockClipboard();

  setUp(() async {
19
    // Fill the clipboard so that the Paste option is available in the text
20
    // selection menu.
21
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
22 23 24 25
    await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
  });

  tearDown(() {
26
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
27 28
  });

29
  testWidgetsWithLeakTracking('Changing query moves cursor to the end of query', (WidgetTester tester) async {
30
    final _TestSearchDelegate delegate = _TestSearchDelegate();
31
    addTearDown(() => delegate.dispose());
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

    await tester.pumpWidget(TestHomePage(delegate: delegate));
    await tester.tap(find.byTooltip('Search'));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 300));

    delegate.query = 'Foo';

    final TextField textField = tester.widget<TextField>(find.byType(TextField));

    expect(
      textField.controller!.selection,
      TextSelection(
        baseOffset: delegate.query.length,
        extentOffset: delegate.query.length,
      ),
    );
  });

51
  testWidgets('Can open and close search', (WidgetTester tester) async {
52
    final _TestSearchDelegate delegate = _TestSearchDelegate();
53 54
    final List<String> selectedResults = <String>[];

55
    await tester.pumpWidget(TestHomePage(
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
      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));
75
    expect(textField.focusNode!.hasFocus, isTrue);
76 77 78 79 80 81 82 83 84 85 86

    // 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']);
  });

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

90
    final _TestSearchDelegate delegate = _TestSearchDelegate();
91
    final List<String?> selectedResults = <String?>[];
92

93
    await tester.pumpWidget(TestHomePage(
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
      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);
110
    expect(find.text('Bottom'), findsOneWidget);
111 112 113

    // Simulate system back button
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
114
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
115 116
    await tester.pumpAndSettle();

117
    expect(selectedResults, <String?>[null]);
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

    // 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);
  });

133
  testWidgets('Hint text color overridden', (WidgetTester tester) async {
134 135
    const String searchHintText = 'Enter search terms';
    final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHintText);
136 137 138 139 140 141 142

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

143 144
    final Text hintText = tester.widget(find.text(searchHintText));
    expect(hintText.style!.color, _TestSearchDelegate.hintTextColor);
145 146
  });

147
  testWidgets('Requests suggestions', (WidgetTester tester) async {
148
    final _TestSearchDelegate delegate = _TestSearchDelegate();
149

150
    await tester.pumpWidget(TestHomePage(
151 152 153 154 155 156
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');
157 158
    expect(delegate.queriesForSuggestions.last, '');
    expect(delegate.queriesForResults, hasLength(0));
159 160

    // Type W o w into search field
161
    delegate.queriesForSuggestions.clear();
162 163 164 165 166 167 168 169 170 171
    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');

172 173
    expect(delegate.queriesForSuggestions, <String>['W', 'Wo', 'Wow']);
    expect(delegate.queriesForResults, hasLength(0));
174 175 176
  });

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

180
    await tester.pumpWidget(TestHomePage(
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
      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));
198
    expect(textField.focusNode!.hasFocus, isFalse);
199
    expect(delegate.queriesForResults, <String>['Wow']);
200 201 202 203 204 205 206 207 208 209 210 211

    // 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']);
  });

212
  testWidgets('Can switch between results and suggestions', (WidgetTester tester) async {
213
    final _TestSearchDelegate delegate = _TestSearchDelegate();
214

215
    await tester.pumpWidget(TestHomePage(
216 217 218
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
219
    await tester.pumpAndSettle();
220 221 222 223 224 225

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

    // Typing query Wow
226
    delegate.queriesForSuggestions.clear();
227
    await tester.enterText(find.byType(TextField), 'Wow');
228
    await tester.pumpAndSettle();
229 230

    expect(delegate.query, 'Wow');
231 232
    expect(delegate.queriesForSuggestions, <String>['Wow']);
    expect(delegate.queriesForResults, hasLength(0));
233 234

    await tester.tap(find.text('Suggestions'));
235
    await tester.pumpAndSettle();
236 237 238 239 240 241

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

    expect(delegate.query, 'Wow');
242 243
    expect(delegate.queriesForSuggestions, <String>['Wow']);
    expect(delegate.queriesForResults, <String>['Wow']);
244 245

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

248
    // Tapping search field to go back to suggestions
249
    await tester.tap(find.byType(TextField));
250
    await tester.pumpAndSettle();
251 252

    textField = tester.widget(find.byType(TextField));
253
    expect(textField.focusNode!.hasFocus, isTrue);
254 255 256

    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Results'), findsNothing);
257 258
    expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow']);
    expect(delegate.queriesForResults, <String>['Wow']);
259 260

    await tester.enterText(find.byType(TextField), 'Foo');
261
    await tester.pumpAndSettle();
262 263

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

    // Go to results again
    await tester.tap(find.text('Suggestions'));
269
    await tester.pumpAndSettle();
270 271 272 273 274

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

    expect(delegate.query, 'Foo');
275 276
    expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow', 'Foo']);
    expect(delegate.queriesForResults, <String>['Wow', 'Foo']);
277 278

    textField = tester.widget(find.byType(TextField));
279
    expect(textField.focusNode!.hasFocus, isFalse);
280 281
  });

282
  testWidgets('Fresh search always starts with empty query', (WidgetTester tester) async {
283
    final _TestSearchDelegate delegate = _TestSearchDelegate();
284

285
    await tester.pumpWidget(TestHomePage(
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
      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 {
303
    final _TestSearchDelegate delegate = _TestSearchDelegate();
304 305 306

    expect(delegate.query, '');

307
    await tester.pumpWidget(TestHomePage(
308 309 310 311 312 313 314 315 316 317 318
      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 {
319
    final _TestSearchDelegate delegate = _TestSearchDelegate();
320 321 322

    delegate.query = 'Foo';

323
    await tester.pumpWidget(TestHomePage(
324 325 326 327 328 329 330 331 332 333
      delegate: delegate,
      passInInitialQuery: true,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

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

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

336
    await tester.pumpWidget(TestHomePage(
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
      delegate: delegate,
      passInInitialQuery: true,
    ));
    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 {
355
    final _TestSearchDelegate delegate = _TestSearchDelegate();
356

357
    await tester.pumpWidget(TestHomePage(
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
      delegate: delegate,
      passInInitialQuery: true,
    ));

    // 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 {
383
    final List<String?> nestedSearchResults = <String?>[];
384
    final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
385 386 387 388 389
      suggestions: 'Nested Suggestions',
      result: 'Nested Result',
    );

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

410
    await tester.pumpWidget(TestHomePage(
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 442 443 444 445 446
      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 {
447 448
    late _TestSearchDelegate delegate;
    final List<String?> nestedSearchResults = <String?>[];
449
    final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
450 451 452
      suggestions: 'Nested Suggestions',
      result: 'Nested Result',
      actions: <Widget>[
453
        Builder(
454
          builder: (BuildContext context) {
455
            return IconButton(
456 457 458 459 460 461 462
              tooltip: 'Close Search',
              icon: const Icon(Icons.close),
              onPressed: () async {
                delegate.close(context, 'Result Foo');
              },
            );
          },
463
        ),
464 465 466 467
      ],
    );

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

488
    await tester.pumpWidget(TestHomePage(
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
      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);
514
    expect(nestedSearchResults, <String?>[null]);
515 516
    expect(selectedResults, <String>['Result Foo']);
  });
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 543 544 545 546 547
  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);
  });

548
  testWidgets('Custom searchFieldStyle value', (WidgetTester tester) async {
549 550
    const String searchHintText = 'Enter search terms';
    const TextStyle searchFieldStyle = TextStyle(color: Colors.red, fontSize: 3);
551

552
    final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHintText, searchFieldStyle: searchFieldStyle);
553

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

558
    final Text hintText = tester.widget(find.text(searchHintText));
559 560
    final TextField textField = tester.widget<TextField>(find.byType(TextField));

561 562
    expect(hintText.style?.color, delegate.searchFieldStyle?.color);
    expect(hintText.style?.fontSize, delegate.searchFieldStyle?.fontSize);
563 564 565
    expect(textField.style?.color, delegate.searchFieldStyle?.color);
    expect(textField.style?.fontSize, delegate.searchFieldStyle?.fontSize);

566 567
  });

568
  testWidgets('keyboard show search button by default', (WidgetTester tester) async {
569
    final _TestSearchDelegate delegate = _TestSearchDelegate();
570

571
    await tester.pumpWidget(TestHomePage(
572 573 574 575 576 577 578
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

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

579
    expect(tester.testTextInput.setClientArgs!['inputAction'], TextInputAction.search.toString());
580
  });
581

582 583 584 585 586 587 588 589 590
  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));
591
    expect(tester.testTextInput.setClientArgs!['inputAction'], TextInputAction.done.toString());
592 593
  });

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
  testWidgets('Custom flexibleSpace value', (WidgetTester tester) async {
    const Widget flexibleSpace = Text('custom flexibleSpace');
    final _TestSearchDelegate delegate = _TestSearchDelegate(flexibleSpace: flexibleSpace);

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

    expect(find.byWidget(flexibleSpace), findsOneWidget);
  });


  group('contributes semantics with custom flexibleSpace', () {
    const Widget flexibleSpace = Text('FlexibleSpace');

    TestSemantics buildExpected({ required String routeName }) {
610 611 612
      final bool isDesktop = debugDefaultTargetPlatformOverride == TargetPlatform.macOS ||
          debugDefaultTargetPlatformOverride == TargetPlatform.windows ||
          debugDefaultTargetPlatformOverride == TargetPlatform.linux;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
      return TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics(
            id: 1,
            textDirection: TextDirection.ltr,
            children: <TestSemantics>[
              TestSemantics(
                id: 2,
                children: <TestSemantics>[
                  TestSemantics(
                    id: 3,
                    flags: <SemanticsFlag>[
                      SemanticsFlag.scopesRoute,
                      SemanticsFlag.namesRoute,
                    ],
                    label: routeName,
                    textDirection: TextDirection.ltr,
                    children: <TestSemantics>[
                      TestSemantics(
                        id: 4,
                        children: <TestSemantics>[
                          TestSemantics(
                            id: 6,
                            children: <TestSemantics>[
                              TestSemantics(
                                id: 8,
                                flags: <SemanticsFlag>[
                                  SemanticsFlag.hasEnabledState,
                                  SemanticsFlag.isButton,
                                  SemanticsFlag.isEnabled,
                                  SemanticsFlag.isFocusable,
                                ],
                                actions: <SemanticsAction>[SemanticsAction.tap],
                                tooltip: 'Back',
                                textDirection: TextDirection.ltr,
                              ),
                              TestSemantics(
                                id: 9,
                                flags: <SemanticsFlag>[
                                  SemanticsFlag.isTextField,
                                  SemanticsFlag.isFocused,
                                  SemanticsFlag.isHeader,
                                  if (debugDefaultTargetPlatformOverride != TargetPlatform.iOS &&
                                    debugDefaultTargetPlatformOverride != TargetPlatform.macOS) SemanticsFlag.namesRoute,
                                ],
                                actions: <SemanticsAction>[
659
                                  if (isDesktop)
660
                                    SemanticsAction.didGainAccessibilityFocus,
661 662
                                  if (isDesktop)
                                    SemanticsAction.didLoseAccessibilityFocus,
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                                  SemanticsAction.tap,
                                  SemanticsAction.setSelection,
                                  SemanticsAction.setText,
                                  SemanticsAction.paste,
                                ],
                                label: 'Search',
                                textDirection: TextDirection.ltr,
                                textSelection: const TextSelection(baseOffset: 0, extentOffset: 0),
                              ),
                              TestSemantics(
                                id: 10,
                                label: 'Bottom',
                                textDirection: TextDirection.ltr,
                              ),
                            ],
                          ),
                          TestSemantics(
                            id: 7,
                            children: <TestSemantics>[
                              TestSemantics(
                                id: 11,
                                label: 'FlexibleSpace',
                                textDirection: TextDirection.ltr,
                              ),
                            ],
                          ),
                        ],
                      ),
                      TestSemantics(
                        id: 5,
                        flags: <SemanticsFlag>[
                          SemanticsFlag.hasEnabledState,
                          SemanticsFlag.isButton,
                          SemanticsFlag.isEnabled,
                          SemanticsFlag.isFocusable,
                        ],
                        actions: <SemanticsAction>[SemanticsAction.tap],
                        label: 'Suggestions',
                        textDirection: TextDirection.ltr,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ],
      );
    }

    testWidgets('includes routeName on Android', (WidgetTester tester) async {
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate(flexibleSpace: flexibleSpace);
      await tester.pumpWidget(TestHomePage(
        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();
    });

    testWidgets('does not include routeName', (WidgetTester tester) async {
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate(flexibleSpace: flexibleSpace);
      await tester.pumpWidget(TestHomePage(
        delegate: delegate,
      ));

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

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

      semantics.dispose();
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS,  TargetPlatform.macOS }));
  });


755
  group('contributes semantics', () {
756
    TestSemantics buildExpected({ required String routeName }) {
757 758 759
      final bool isDesktop = debugDefaultTargetPlatformOverride == TargetPlatform.macOS ||
                             debugDefaultTargetPlatformOverride == TargetPlatform.windows ||
                             debugDefaultTargetPlatformOverride == TargetPlatform.linux;
760
      return TestSemantics.root(
761
        children: <TestSemantics>[
762
          TestSemantics(
763 764 765
            id: 1,
            textDirection: TextDirection.ltr,
            children: <TestSemantics>[
766
              TestSemantics(
767
                id: 2,
768
                children: <TestSemantics>[
769
                  TestSemantics(
770 771 772 773 774 775 776
                    id: 7,
                    flags: <SemanticsFlag>[
                      SemanticsFlag.scopesRoute,
                      SemanticsFlag.namesRoute,
                    ],
                    label: routeName,
                    textDirection: TextDirection.ltr,
777
                    children: <TestSemantics>[
778
                      TestSemantics(
779 780 781 782 783 784 785 786 787 788
                        id: 9,
                        children: <TestSemantics>[
                          TestSemantics(
                            id: 10,
                            flags: <SemanticsFlag>[
                              SemanticsFlag.hasEnabledState,
                              SemanticsFlag.isButton,
                              SemanticsFlag.isEnabled,
                              SemanticsFlag.isFocusable,
                            ],
789
                            actions: <SemanticsAction>[SemanticsAction.tap],
790
                            tooltip: 'Back',
791 792 793 794 795 796 797 798 799 800 801 802
                            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>[
803
                              if (isDesktop)
804
                                SemanticsAction.didGainAccessibilityFocus,
805 806
                              if (isDesktop)
                                SemanticsAction.didLoseAccessibilityFocus,
807 808
                              SemanticsAction.tap,
                              SemanticsAction.setSelection,
809
                              SemanticsAction.setText,
810 811 812 813 814 815
                              SemanticsAction.paste,
                            ],
                            label: 'Search',
                            textDirection: TextDirection.ltr,
                            textSelection: const TextSelection(baseOffset: 0, extentOffset: 0),
                          ),
816 817 818 819 820
                          TestSemantics(
                            id: 14,
                            label: 'Bottom',
                            textDirection: TextDirection.ltr,
                          ),
821 822 823 824
                        ],
                      ),
                      TestSemantics(
                        id: 8,
825 826
                        flags: <SemanticsFlag>[
                          SemanticsFlag.hasEnabledState,
827
                          SemanticsFlag.isButton,
828
                          SemanticsFlag.isEnabled,
829
                          SemanticsFlag.isFocusable,
830 831
                        ],
                        actions: <SemanticsAction>[SemanticsAction.tap],
832
                        label: 'Suggestions',
833 834 835 836 837 838 839 840 841 842 843 844 845
                        textDirection: TextDirection.ltr,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ],
      );
    }

    testWidgets('includes routeName on Android', (WidgetTester tester) async {
846 847 848
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate();
      await tester.pumpWidget(TestHomePage(
849 850 851 852 853 854
        delegate: delegate,
      ));

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

855 856 857 858 859 860
      expect(semantics, hasSemantics(
        buildExpected(routeName: 'Search'),
        ignoreId: true,
        ignoreRect: true,
        ignoreTransform: true,
      ));
861 862 863 864

      semantics.dispose();
    });

Dan Field's avatar
Dan Field committed
865
    testWidgets('does not include routeName', (WidgetTester tester) async {
866 867 868
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate();
      await tester.pumpWidget(TestHomePage(
869 870 871 872 873 874
        delegate: delegate,
      ));

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

875 876 877 878 879 880
      expect(semantics, hasSemantics(
        buildExpected(routeName: ''),
        ignoreId: true,
        ignoreRect: true,
        ignoreTransform: true,
      ));
881 882

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

886
  testWidgets('Custom searchFieldDecorationTheme value', (WidgetTester tester) async {
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    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);
  });

902 903
  // Regression test for: https://github.com/flutter/flutter/issues/66781
  testWidgets('text in search bar contrasts background (light mode)', (WidgetTester tester) async {
904
    final ThemeData themeData = ThemeData(useMaterial3: false);
905 906 907 908 909 910 911 912 913 914
    final _TestSearchDelegate delegate = _TestSearchDelegate(
      defaultAppBarTheme: true,
    );
    const String query = 'search query';
    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: query,
      themeData: themeData,
    ));
915

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

919
    final Material appBarBackground = tester.widgetList<Material>(find.descendant(
920 921
      of: find.byType(AppBar),
      matching: find.byType(Material),
922
    )).first;
923
    expect(appBarBackground.color, Colors.white);
924

925
    final TextField textField = tester.widget<TextField>(find.byType(TextField));
926
    expect(textField.style!.color, themeData.textTheme.bodyLarge!.color);
927
    expect(textField.style!.color, isNot(equals(Colors.white)));
928 929 930 931
  });

  // Regression test for: https://github.com/flutter/flutter/issues/66781
  testWidgets('text in search bar contrasts background (dark mode)', (WidgetTester tester) async {
932
    final ThemeData themeData = ThemeData.dark(useMaterial3: false);
933 934 935 936 937 938 939 940 941 942
    final _TestSearchDelegate delegate = _TestSearchDelegate(
      defaultAppBarTheme: true,
    );
    const String query = 'search query';
    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: query,
      themeData: themeData,
    ));
943

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

947
    final Material appBarBackground = tester.widgetList<Material>(find.descendant(
948 949
      of: find.byType(AppBar),
      matching: find.byType(Material),
950
    )).first;
951
    expect(appBarBackground.color, themeData.primaryColor);
952

953
    final TextField textField = tester.widget<TextField>(find.byType(TextField));
954
    expect(textField.style!.color, themeData.textTheme.bodyLarge!.color);
955
    expect(textField.style!.color, isNot(equals(themeData.primaryColor)));
956
  });
957 958

  // Regression test for: https://github.com/flutter/flutter/issues/78144
959
  testWidgets('`Leading`, `Actions` and `FlexibleSpace` nullable test', (WidgetTester tester) async {
960
    // The search delegate page is displayed with no issues
961
    // even with a null return values for [buildLeading], [buildActions] and [flexibleSpace].
962
    final _TestEmptySearchDelegate delegate = _TestEmptySearchDelegate();
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
    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']);
  });
996 997 998 999 1000

  testWidgets('showSearch with useRootNavigator', (WidgetTester tester) async {
    final _MyNavigatorObserver rootObserver = _MyNavigatorObserver();
    final _MyNavigatorObserver localObserver = _MyNavigatorObserver();

1001
    final _TestEmptySearchDelegate delegate = _TestEmptySearchDelegate();
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

    await tester.pumpWidget(MaterialApp(
      navigatorObservers: <NavigatorObserver>[rootObserver],
      home: Navigator(
        observers: <NavigatorObserver>[localObserver],
        onGenerateRoute: (RouteSettings settings) {
          if (settings.name == 'nested') {
            return MaterialPageRoute<dynamic>(
              builder: (BuildContext context) => Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  TextButton(
                      onPressed: () async {
                        await showSearch(context: context, delegate: delegate, useRootNavigator: true);
                      },
                      child: const Text('showSearchRootNavigator')),
                  TextButton(
                      onPressed: () async {
                        await showSearch(context: context, delegate: delegate);
                      },
                      child: const Text('showSearchLocalNavigator')),
                ],
              ),
              settings: settings,
            );
          }
          throw UnimplementedError();
        },
        initialRoute: 'nested',
      ),
    ));

    expect(rootObserver.pushCount, 0);
    expect(localObserver.pushCount, 0);

    // showSearch normal and back
    await tester.tap(find.text('showSearchLocalNavigator'));
    await tester.pumpAndSettle();
    await tester.tap(find.byTooltip('Close'));
    await tester.pumpAndSettle();
    expect(rootObserver.pushCount, 0);
    expect(localObserver.pushCount, 1);

    // showSearch with rootNavigator
    await tester.tap(find.text('showSearchRootNavigator'));
    await tester.pumpAndSettle();
    await tester.tap(find.byTooltip('Close'));
    await tester.pumpAndSettle();
    expect(rootObserver.pushCount, 1);
    expect(localObserver.pushCount, 1);
  });
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

  testWidgets('Query text field shows toolbar initially', (WidgetTester tester) async {
    // This is a regression test for https://github.com/flutter/flutter/issues/95588

    final _TestSearchDelegate delegate = _TestSearchDelegate();
    final List<String> selectedResults = <String>[];

    await tester.pumpWidget(TestHomePage(
      delegate: delegate,
      results: selectedResults,
    ));

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

    final Finder textFieldFinder = find.byType(TextField);
    final TextField textField = tester.widget<TextField>(textFieldFinder);
    expect(textField.controller!.text.length, 0);

    mockClipboard.handleMethodCall(const MethodCall(
      'Clipboard.setData',
      <String, dynamic>{
        'text': 'pasteablestring',
      },
    ));

    // Long press shows toolbar.
    await tester.longPress(textFieldFinder);
    await tester.pump();
    expect(find.text('Paste'), findsOneWidget);

    await tester.tap(find.text('Paste'));
    await tester.pump();
    expect(textField.controller!.text.length, 15);
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
1089 1090 1091 1092
}

class TestHomePage extends StatelessWidget {
  const TestHomePage({
1093
    super.key,
1094
    this.results,
1095
    required this.delegate,
1096
    this.passInInitialQuery = false,
1097
    this.initialQuery,
1098
    this.themeData,
1099
  });
1100

1101
  final List<String?>? results;
1102 1103
  final SearchDelegate<String> delegate;
  final bool passInInitialQuery;
1104
  final ThemeData? themeData;
1105
  final String? initialQuery;
1106 1107 1108

  @override
  Widget build(BuildContext context) {
1109
    return MaterialApp(
1110
      theme: themeData,
1111
      home: Builder(builder: (BuildContext context) {
1112 1113
        return Scaffold(
          appBar: AppBar(
1114 1115
            title: const Text('HomeTitle'),
            actions: <Widget>[
1116
              IconButton(
1117 1118 1119
                tooltip: 'Search',
                icon: const Icon(Icons.search),
                onPressed: () async {
1120
                  String? selectedResult;
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
                  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({
1147 1148 1149
    this.suggestions = 'Suggestions',
    this.result = 'Result',
    this.actions = const <Widget>[],
1150
    this.flexibleSpace ,
1151
    this.defaultAppBarTheme = false,
1152 1153
    super.searchFieldDecorationTheme,
    super.searchFieldStyle,
1154
    String? searchHint,
1155
    super.textInputAction,
1156 1157 1158
  }) : super(
          searchFieldLabel: searchHint,
        );
1159

1160
  final bool defaultAppBarTheme;
1161 1162 1163
  final String suggestions;
  final String result;
  final List<Widget> actions;
1164
  final Widget? flexibleSpace;
1165
  static const Color hintTextColor = Colors.green;
1166 1167 1168

  @override
  ThemeData appBarTheme(BuildContext context) {
1169 1170 1171
    if (defaultAppBarTheme) {
      return super.appBarTheme(context);
    }
1172
    final ThemeData theme = Theme.of(context);
1173
    return theme.copyWith(
1174 1175 1176 1177 1178 1179 1180
      inputDecorationTheme: searchFieldDecorationTheme ??
          InputDecorationTheme(
            hintStyle: searchFieldStyle ??
                const TextStyle(
                  color: hintTextColor,
                ),
          ),
1181 1182
    );
  }
1183 1184 1185

  @override
  Widget buildLeading(BuildContext context) {
1186
    return IconButton(
1187 1188 1189 1190 1191 1192 1193 1194
      tooltip: 'Back',
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, result);
      },
    );
  }

1195 1196
  final List<String> queriesForSuggestions = <String>[];
  final List<String> queriesForResults = <String>[];
1197 1198 1199

  @override
  Widget buildSuggestions(BuildContext context) {
1200
    queriesForSuggestions.add(query);
1201
    return ElevatedButton(
1202 1203 1204
      onPressed: () {
        showResults(context);
      },
1205
      child: Text(suggestions),
1206 1207 1208 1209 1210
    );
  }

  @override
  Widget buildResults(BuildContext context) {
1211
    queriesForResults.add(query);
1212 1213 1214 1215 1216 1217 1218
    return const Text('Results');
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return actions;
  }
1219

1220 1221 1222 1223 1224
  @override
  Widget? buildFlexibleSpace(BuildContext context) {
    return flexibleSpace;
  }

1225 1226 1227 1228 1229 1230 1231
  @override
  PreferredSizeWidget buildBottom(BuildContext context) {
    return const PreferredSize(
      preferredSize: Size.fromHeight(56.0),
      child: Text('Bottom'),
    );
  }
1232
}
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

class _TestEmptySearchDelegate extends SearchDelegate<String> {
  @override
  Widget? buildLeading(BuildContext context) => null;

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

  @override
  Widget buildSuggestions(BuildContext context) {
1243
    return ElevatedButton(
1244 1245 1246
      onPressed: () {
        showResults(context);
      },
1247
      child: const Text('Suggestions'),
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    );
  }

  @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: () {
1264
          close(context, 'Result');
1265 1266 1267 1268 1269
        },
      ),
    );
  }
}
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

class _MyNavigatorObserver extends NavigatorObserver {
  int pushCount = 0;

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    // don't count the root route
    if (<String>['nested', '/'].contains(route.settings.name)) {
      return;
    }
    pushCount++;
  }
}