-
Notifications
You must be signed in to change notification settings - Fork 30.3k
Expand file tree
/
Copy pathfinders.dart
More file actions
1916 lines (1687 loc) · 63.9 KB
/
finders.dart
File metadata and controls
1916 lines (1687 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
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
509
510
511
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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
659
660
661
662
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
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
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:flutter/material.dart';
///
/// @docImport 'widget_tester.dart';
library;
import 'dart:ui';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart' show Tooltip;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'binding.dart';
import 'tree_traversal.dart';
/// Signature for [CommonFinders.byWidgetPredicate].
typedef WidgetPredicate = bool Function(Widget widget);
/// Signature for [CommonFinders.byElementPredicate].
typedef ElementPredicate = bool Function(Element element);
/// Signature for [CommonSemanticsFinders.byPredicate].
typedef SemanticsNodePredicate = bool Function(SemanticsNode node);
/// Signature for [FinderBase.describeMatch].
typedef DescribeMatchCallback = String Function(Plurality plurality);
/// Returns true if [renderObject] is equal to [target] or is an ancestor of
/// [target] in the render tree.
///
/// This is useful for hit testing because some render objects (like
/// [RenderTransform]) don't add themselves to the hit test path but instead
/// just transform the hit test point and pass it to their children.
bool isRenderObjectAncestorOfTarget(RenderObject renderObject, HitTestTarget target) {
if (target == renderObject) {
return true;
}
if (target is RenderObject) {
for (RenderObject? current = target.parent; current != null; current = current.parent) {
if (current == renderObject) {
return true;
}
}
}
return false;
}
/// The `CandidateType` of finders that search for and filter substrings,
/// within static text rendered by [RenderParagraph]s.
final class TextRangeContext {
const TextRangeContext._(this.view, this.renderObject, this.textRange);
/// The [View] containing the static text.
///
/// This is used for hit-testing.
final View view;
/// The RenderObject that contains the static text.
final RenderParagraph renderObject;
/// The [TextRange] of the substring within [renderObject]'s text.
final TextRange textRange;
@override
String toString() => 'TextRangeContext($view, $renderObject, $textRange)';
}
/// Some frequently used [Finder]s and [SemanticsFinder]s.
const CommonFinders find = CommonFinders._();
// Examples can assume:
// typedef Button = Placeholder;
// late WidgetTester tester;
// late String filePath;
// late Key backKey;
/// Provides lightweight syntax for getting frequently used [Finder]s and
/// [SemanticsFinder]s through [semantics].
///
/// This class is instantiated once, as [find].
class CommonFinders {
const CommonFinders._();
/// Some frequently used semantics finders.
CommonSemanticsFinders get semantics => const CommonSemanticsFinders._();
/// Some frequently used text range finders.
CommonTextRangeFinders get textRange => const CommonTextRangeFinders._();
/// Finds [Text], [EditableText], and optionally [RichText] widgets
/// containing string equal to the `text` argument.
///
/// If `findRichText` is false, all standalone [RichText] widgets are
/// ignored and `text` is matched with [Text.data] or [Text.textSpan].
/// If `findRichText` is true, [RichText] widgets (and therefore also
/// [Text] and [Text.rich] widgets) are matched by comparing the
/// [InlineSpan.toPlainText] with the given `text`.
///
/// For [EditableText] widgets, the `text` is always compared to the current
/// value of the [EditableText.controller].
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Back'), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], and [EditableText] widgets that
/// contain the "Back" string.
///
/// ```dart
/// expect(find.text('Close', findRichText: true), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], [EditableText], as well as standalone
/// [RichText] widgets that contain the "Close" string.
Finder text(String text, {bool findRichText = false, bool skipOffstage = true}) {
return _TextWidgetFinder(text, findRichText: findRichText, skipOffstage: skipOffstage);
}
/// Finds [Text] and [EditableText], and optionally [RichText] widgets
/// which contain the given `pattern` argument.
///
/// If `findRichText` is false, all standalone [RichText] widgets are
/// ignored and `pattern` is matched with [Text.data] or [Text.textSpan].
/// If `findRichText` is true, [RichText] widgets (and therefore also
/// [Text] and [Text.rich] widgets) are matched by comparing the
/// [InlineSpan.toPlainText] with the given `pattern`.
///
/// For [EditableText] widgets, the `pattern` is always compared to the current
/// value of the [EditableText.controller].
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// ## Sample code
///
/// ```dart
/// expect(find.textContaining('Back'), findsOneWidget);
/// expect(find.textContaining(RegExp(r'(\w+)')), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], and [EditableText] widgets that
/// contain the given pattern : 'Back' or RegExp(r'(\w+)').
///
/// ```dart
/// expect(find.textContaining('Close', findRichText: true), findsOneWidget);
/// expect(find.textContaining(RegExp(r'(\w+)'), findRichText: true), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], [EditableText], as well as standalone
/// [RichText] widgets that contain the given pattern : 'Close' or RegExp(r'(\w+)').
Finder textContaining(Pattern pattern, {bool findRichText = false, bool skipOffstage = true}) {
return _TextContainingWidgetFinder(
pattern,
findRichText: findRichText,
skipOffstage: skipOffstage,
);
}
/// Looks for widgets that contain a [Text] descendant with `text`
/// in it.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button with text 'Update' in it:
/// const Button(
/// child: Text('Update')
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.widgetWithText(Button, 'Update'));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder widgetWithText(Type widgetType, String text, {bool skipOffstage = true}) {
return find.ancestor(
of: find.text(text, skipOffstage: skipOffstage),
matching: find.byType(widgetType, skipOffstage: skipOffstage),
);
}
/// Finds [Image] and [FadeInImage] widgets containing `image` equal to the
/// `image` argument.
///
/// ## Sample code
///
/// ```dart
/// expect(find.image(FileImage(File(filePath))), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder image(ImageProvider image, {bool skipOffstage = true}) =>
_ImageWidgetFinder(image, skipOffstage: skipOffstage);
/// Finds widgets by searching for one with the given `key`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byKey(backKey), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byKey(Key key, {bool skipOffstage = true}) =>
_KeyWidgetFinder(key, skipOffstage: skipOffstage);
/// Finds widgets by searching for widgets implementing a particular type.
///
/// This matcher accepts subtypes. For example a
/// `bySubtype<StatefulWidget>()` will find any stateful widget.
///
/// ## Sample code
///
/// ```dart
/// expect(find.bySubtype<IconButton>(), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// See also:
/// * [byType], which does not do subtype tests.
Finder bySubtype<T extends Widget>({bool skipOffstage = true}) =>
_SubtypeWidgetFinder<T>(skipOffstage: skipOffstage);
/// Finds widgets by searching for widgets with a particular type.
///
/// This does not do subclass tests, so for example
/// `byType(StatefulWidget)` will never find anything since [StatefulWidget]
/// is an abstract class.
///
/// The `type` argument must be a subclass of [Widget].
///
/// ## Sample code
///
/// ```dart
/// expect(find.byType(IconButton), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// See also:
/// * [bySubtype], which allows subtype tests.
Finder byType(Type type, {bool skipOffstage = true}) =>
_TypeWidgetFinder(type, skipOffstage: skipOffstage);
/// Finds [Icon] widgets containing icon data equal to the `icon`
/// argument.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byIcon(Icons.inbox), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byIcon(IconData icon, {bool skipOffstage = true}) =>
_IconWidgetFinder(icon, skipOffstage: skipOffstage);
/// Looks for widgets that contain an [Icon] descendant displaying [IconData]
/// `icon` in it.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button with icon 'arrow_forward' in it:
/// const Button(
/// child: Icon(Icons.arrow_forward)
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.widgetWithIcon(Button, Icons.arrow_forward));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder widgetWithIcon(Type widgetType, IconData icon, {bool skipOffstage = true}) {
return find.ancestor(of: find.byIcon(icon), matching: find.byType(widgetType));
}
/// Looks for widgets that contain an [Image] descendant displaying
/// [ImageProvider] `image` in it.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button with an image in it:
/// Button(
/// child: Image.file(File(filePath))
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.widgetWithImage(Button, FileImage(File(filePath))));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder widgetWithImage(Type widgetType, ImageProvider image, {bool skipOffstage = true}) {
return find.ancestor(of: find.image(image), matching: find.byType(widgetType));
}
/// Finds widgets by searching for elements with a particular type.
///
/// This does not do subclass tests, so for example
/// `byElementType(VirtualViewportElement)` will never find anything
/// since [RenderObjectElement] is an abstract class.
///
/// The `type` argument must be a subclass of [Element].
///
/// ## Sample code
///
/// ```dart
/// expect(find.byElementType(SingleChildRenderObjectElement), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byElementType(Type type, {bool skipOffstage = true}) =>
_ElementTypeWidgetFinder(type, skipOffstage: skipOffstage);
/// Finds widgets whose current widget is the instance given by the `widget`
/// argument.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button created like this:
/// Widget myButton = const Button(
/// child: Text('Update')
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.byWidget(myButton));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byWidget(Widget widget, {bool skipOffstage = true}) =>
_ExactWidgetFinder(widget, skipOffstage: skipOffstage);
/// Finds widgets using a widget `predicate`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byWidgetPredicate(
/// (Widget widget) => widget is Tooltip && widget.message == 'Back',
/// description: 'with tooltip "Back"',
/// ), findsOneWidget);
/// ```
///
/// If `description` is provided, then this uses it as the description of the
/// [Finder] and appears, for example, in the error message when the finder
/// fails to locate the desired widget. Otherwise, the description prints the
/// signature of the predicate function.
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byWidgetPredicate(
WidgetPredicate predicate, {
String? description,
bool skipOffstage = true,
}) {
return _WidgetPredicateWidgetFinder(
predicate,
description: description,
skipOffstage: skipOffstage,
);
}
/// Finds [RawTooltip] or [Tooltip] widgets with the given `message`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byTooltip('Back'), findsOneWidget);
/// expect(find.byTooltip(RegExp('Back.*')), findsNWidgets(2));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byTooltip(Pattern message, {bool skipOffstage = true}) {
return byWidgetPredicate((Widget widget) {
// Compare RawTooltip's semantics tooltip with the given message.
// However, Tooltip's message needs to be checked directly if:
// 1. Tooltip.excludeFromSemantics is true, since in this case Tooltip
// provides no semantics tooltip to the underlying RawTooltip.
// 2. Tooltip.message and Tooltip.richMessage are empty, since in this
// case no RawTooltip is created.
if (widget is Tooltip) {
final String tooltipMessage = widget.message ?? widget.richMessage!.toPlainText();
if ((widget.excludeFromSemantics ?? false) || tooltipMessage.isEmpty) {
return message is RegExp ? message.hasMatch(tooltipMessage) : tooltipMessage == message;
}
}
return widget is RawTooltip &&
(message is RegExp
? message.hasMatch(widget.semanticsTooltip ?? '')
: widget.semanticsTooltip == message);
}, skipOffstage: skipOffstage);
}
/// Finds widgets using an element `predicate`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byElementPredicate(
/// // Finds elements of type SingleChildRenderObjectElement, including
/// // those that are actually subclasses of that type.
/// // (contrast with byElementType, which only returns exact matches)
/// (Element element) => element is SingleChildRenderObjectElement,
/// description: '$SingleChildRenderObjectElement element',
/// ), findsOneWidget);
/// ```
///
/// If `description` is provided, then this uses it as the description of the
/// [Finder] and appears, for example, in the error message when the finder
/// fails to locate the desired widget. Otherwise, the description prints the
/// signature of the predicate function.
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byElementPredicate(
ElementPredicate predicate, {
String? description,
bool skipOffstage = true,
}) {
return _ElementPredicateWidgetFinder(
predicate,
description: description,
skipOffstage: skipOffstage,
);
}
/// Finds widgets that are descendants of the `of` parameter and that match
/// the `matching` parameter.
///
/// ## Sample code
///
/// ```dart
/// expect(find.descendant(
/// of: find.widgetWithText(Row, 'label_1'),
/// matching: find.text('value_1'),
/// ), findsOneWidget);
/// ```
///
/// If the `matchRoot` argument is true then the widget(s) specified by `of`
/// will be matched along with the descendants.
///
/// If the `skipOffstage` argument is true (the default), then nodes that are
/// [Offstage] or that are from inactive [Route]s are skipped.
Finder descendant({
required FinderBase<Element> of,
required FinderBase<Element> matching,
bool matchRoot = false,
bool skipOffstage = true,
}) {
return _DescendantWidgetFinder(of, matching, matchRoot: matchRoot, skipOffstage: skipOffstage);
}
/// Finds widgets that are ancestors of the `of` parameter and that match
/// the `matching` parameter.
///
/// ## Sample code
///
/// ```dart
/// // Test if a Text widget that contains 'faded' is the
/// // descendant of an Opacity widget with opacity 0.5:
/// expect(
/// tester.widget<Opacity>(
/// find.ancestor(
/// of: find.text('faded'),
/// matching: find.byType(Opacity),
/// )
/// ).opacity,
/// 0.5
/// );
/// ```
///
/// If the `matchRoot` argument is true then the widget(s) specified by `of`
/// will be matched along with the ancestors.
Finder ancestor({
required FinderBase<Element> of,
required FinderBase<Element> matching,
bool matchRoot = false,
}) {
return _AncestorWidgetFinder(of, matching, matchLeaves: matchRoot);
}
/// Finds a standard "back" button.
///
/// A common element on many user interfaces is the "back" button. This is
/// the button which takes the user back to the previous page/screen/state.
///
/// It is useful in tests to be able to find these buttons, both for tapping
/// them or verifying their existence, but because different platforms and
/// locales have different icons representing them with different labels and
/// tooltips, it's not desirable to have to look them up by these attributes.
///
/// This finder uses the [StandardComponentType] enum to look for buttons that
/// have the key associated with [StandardComponentType.backButton]. If
/// another widget is assigned that key, then it too will be considered an
/// "official" back button in the widget tree, allowing this matcher to still
/// find it even though it might use a different icon or tooltip.
///
/// ## Sample code
///
/// ```dart
/// expect(find.backButton(), findsOneWidget);
/// ```
///
/// See also:
///
/// * [StandardComponentType], the enum that enumerates components that are
/// both common in user interfaces, but which also can vary slightly in
/// presentation across different platforms, locales, and devices.
/// * [BackButton], the Flutter Material widget that represents the back
/// button.
Finder backButton() {
return byKey(StandardComponentType.backButton.key);
}
/// Finds a standard "close" button.
///
/// A common element on many user interfaces is the "close" button. This is
/// the button which closes or cancels whatever it is attached to.
///
/// It is useful in tests to be able to find these buttons, both for tapping
/// them or verifying their existence, but because different platforms and
/// locales have different icons representing them with different labels and
/// tooltips, it's not desirable to have to look them up by these attributes.
///
/// This finder uses the [StandardComponentType] enum to look for buttons that
/// have the key associated with [StandardComponentType.closeButton]. If
/// another widget is assigned that key, then it too will be considered an
/// "official" close button in the widget tree, allowing this matcher to still
/// find it even though it might use a different icon or tooltip.
///
/// ## Sample code
///
/// ```dart
/// expect(find.closeButton(), findsOneWidget);
/// ```
///
/// See also:
///
/// * [StandardComponentType], the enum that enumerates components that are
/// both common in user interfaces, but which also can vary slightly in
/// presentation across different platforms, locales, and devices.
/// * [CloseButton], the Flutter Material widget that represents a close
/// button.
Finder closeButton() {
return byKey(StandardComponentType.closeButton.key);
}
/// Finds [Semantics] widgets matching the given `label`, either by
/// [RegExp.hasMatch] or string equality.
///
/// The framework may combine semantics labels in certain scenarios, such as
/// when multiple [Text] widgets are in a [TextButton] widget. In such a
/// case, it may be preferable to match by regular expression. Consumers of
/// this API __must not__ introduce unsuitable content into the semantics tree
/// for the purposes of testing; in particular, you should prefer matching by
/// regular expression rather than by string if the framework has combined
/// your semantics, and not try to force the framework to break up the
/// semantics nodes. Breaking up the nodes would have an undesirable effect on
/// screen readers and other accessibility services.
///
/// ## Sample code
///
/// ```dart
/// expect(find.bySemanticsLabel('Back'), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder bySemanticsLabel(Pattern label, {bool skipOffstage = true}) {
final String description = switch (label) {
final RegExp regExp => 'a semantics label matching the pattern "${regExp.pattern}"',
final String labelString => 'a semantics label named "$labelString"',
_ => 'a semantics label matching "$label"',
};
return _bySemanticsProperty(
label,
description,
(SemanticsNode? semantics) => semantics?.label,
skipOffstage: skipOffstage,
);
}
/// Finds [Semantics] widgets matching the given `identifier`, either by
/// [RegExp.hasMatch] or string equality.
///
/// This allows matching against the identifier of a [Semantics] widget, which
/// is a unique identifier for the widget in the semantics tree. This is
/// exposed to offer a unified way widget tests and e2e tests can match
/// against a [Semantics] widget.
///
/// ## Sample code
///
/// ```dart
/// expect(find.bySemanticsIdentifier('Back'), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder bySemanticsIdentifier(Pattern identifier, {bool skipOffstage = true}) {
final String description = switch (identifier) {
final RegExp regExp => 'a semantics identifier matching the pattern "${regExp.pattern}"',
final String id => 'a semantics identifier named "$id"',
_ => 'a semantics identifier matching "$identifier"',
};
return _bySemanticsProperty(
identifier,
description,
(SemanticsNode? semantics) => semantics?.identifier,
skipOffstage: skipOffstage,
);
}
Finder _bySemanticsProperty(
Pattern pattern,
String description,
String? Function(SemanticsNode?) propertyGetter, {
bool skipOffstage = true,
}) {
if (!SemanticsBinding.instance.semanticsEnabled) {
throw StateError(
'Semantics are not enabled. '
'Make sure to call tester.ensureSemantics() before using '
'this finder, and call dispose on its return value after.',
);
}
return byElementPredicate(
(Element element) {
// Multiple elements can have the same renderObject - we want the "owner"
// of the renderObject, i.e. the RenderObjectElement.
if (element is! RenderObjectElement) {
return false;
}
final String? propertyValue = propertyGetter(element.renderObject.debugSemantics);
if (propertyValue == null) {
return false;
}
return pattern is RegExp ? pattern.hasMatch(propertyValue) : pattern == propertyValue;
},
description: description,
skipOffstage: skipOffstage,
);
}
}
/// Provides lightweight syntax for getting frequently used semantics finders.
///
/// This class is instantiated once, as [CommonFinders.semantics], under [find].
class CommonSemanticsFinders {
const CommonSemanticsFinders._();
/// Finds an ancestor of `of` that matches `matching`.
///
/// If `matchRoot` is true, then the results of `of` are included in the
/// search and results.
FinderBase<SemanticsNode> ancestor({
required FinderBase<SemanticsNode> of,
required FinderBase<SemanticsNode> matching,
bool matchRoot = false,
}) {
return _AncestorSemanticsFinder(of, matching, matchRoot);
}
/// Finds a descendant of `of` that matches `matching`.
///
/// If `matchRoot` is true, then the results of `of` are included in the
/// search and results.
FinderBase<SemanticsNode> descendant({
required FinderBase<SemanticsNode> of,
required FinderBase<SemanticsNode> matching,
bool matchRoot = false,
}) {
return _DescendantSemanticsFinder(of, matching, matchRoot: matchRoot);
}
/// Finds any [SemanticsNode]s matching the given `predicate`.
///
/// If `describeMatch` is provided, it will be used to describe the
/// [FinderBase] and [FinderResult]s.
/// {@macro flutter_test.finders.FinderBase.describeMatch}
///
/// {@template flutter_test.finders.CommonSemanticsFinders.viewParameter}
/// The `view` provided will be used to determine the semantics tree where
/// the search will be evaluated. If not provided, the search will be
/// evaluated against the semantics tree of [WidgetTester.view].
/// {@endtemplate}
SemanticsFinder byPredicate(
SemanticsNodePredicate predicate, {
DescribeMatchCallback? describeMatch,
FlutterView? view,
}) {
return _PredicateSemanticsFinder(predicate, describeMatch, view);
}
/// Finds any [SemanticsNode]s that has a [SemanticsNode.label] that matches
/// the given `label`.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byLabel(Pattern label, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => _matchesPattern(node.label, label),
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with label "$label"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has a [SemanticsNode.value] that matches
/// the given `value`.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byValue(Pattern value, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => _matchesPattern(node.value, value),
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with value "$value"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has a [SemanticsNode.hint] that matches
/// the given `hint`.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byHint(Pattern hint, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => _matchesPattern(node.hint, hint),
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with hint "$hint"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has the given [SemanticsAction].
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byAction(SemanticsAction action, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => node.getSemanticsData().hasAction(action),
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with action "$action"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has at least one of the given
/// [SemanticsAction]s.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byAnyAction(List<SemanticsAction> actions, {FlutterView? view}) {
final int actionsInt = actions.fold(
0,
(int value, SemanticsAction action) => value | action.index,
);
return byPredicate(
(SemanticsNode node) => node.getSemanticsData().actions & actionsInt != 0,
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with any of the following actions: $actions',
view: view,
);
}
/// Finds any [SemanticsNode]s that has the given [SemanticsFlag].
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byFlag(SemanticsFlag flag, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => node.hasFlag(flag),
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with flag "$flag"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has at least one of the given
/// [SemanticsFlag]s.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byAnyFlag(List<SemanticsFlag> flags, {FlutterView? view}) {
final int flagsInt = flags.fold(0, (int value, SemanticsFlag flag) => value | flag.index);
return byPredicate(
(SemanticsNode node) => node.getSemanticsData().flags & flagsInt != 0,
describeMatch: (Plurality plurality) =>
'${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with any of the following flags: $flags',
view: view,
);
}
/// Finds any [SemanticsNode]s that can scroll in at least one direction.
///
/// If `axis` is provided, then the search will be limited to scrollable nodes
/// that can scroll in the given axis. If `axis` is not provided, then both
/// horizontal and vertical scrollable nodes will be found.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder scrollable({Axis? axis, FlutterView? view}) {
return byAnyAction(<SemanticsAction>[
if (axis == null || axis == Axis.vertical) ...<SemanticsAction>[
SemanticsAction.scrollUp,
SemanticsAction.scrollDown,
],
if (axis == null || axis == Axis.horizontal) ...<SemanticsAction>[
SemanticsAction.scrollLeft,
SemanticsAction.scrollRight,
],
]);
}
bool _matchesPattern(String target, Pattern pattern) {
if (pattern is RegExp) {
return pattern.hasMatch(target);
} else {
return pattern == target;
}
}
}
/// Provides lightweight syntax for getting frequently used text range finders.
///
/// This class is instantiated once, as [CommonFinders.textRange], under [find].
final class CommonTextRangeFinders {
const CommonTextRangeFinders._();
/// Finds all non-overlapping occurrences of the given `substring` in the
/// static text widgets and returns the [TextRange]s.
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// static text inside widgets that are [Offstage], or that are from inactive
/// [Route]s.
///
/// If the `descendentOf` argument is non-null, this method only searches in
/// the descendants of that parameter for the given substring.
///
/// This finder uses the [Pattern.allMatches] method to match the substring in
/// the text. After finding a matching substring in the text, the method
/// continues the search from the end of the match, thus skipping overlapping
/// occurrences of the substring.
FinderBase<TextRangeContext> ofSubstring(
String substring, {
bool skipOffstage = true,
FinderBase<Element>? descendentOf,
}) {
final textWidgetFinder = _TextContainingWidgetFinder(
substring,
skipOffstage: skipOffstage,
findRichText: true,
);
final Finder elementFinder = descendentOf == null
? textWidgetFinder
: _DescendantWidgetFinder(
descendentOf,
textWidgetFinder,
matchRoot: true,
skipOffstage: skipOffstage,
);
return _StaticTextRangeFinder(elementFinder, substring);
}
}
/// Describes how a string of text should be pluralized.
enum Plurality {
/// Text should be pluralized to describe zero items.
zero,
/// Text should be pluralized to describe a single item.
one,
/// Text should be pluralized to describe more than one item.
many;
static Plurality _fromNum(num source) {
assert(source >= 0, 'A Plurality can only be created with a positive number.');
return switch (source) {
0 => Plurality.zero,
1 => Plurality.one,
_ => Plurality.many,
};
}
}
/// Encapsulates the logic for searching a list of candidates and filtering the
/// candidates to only those that meet the requirements defined by the finder.
///
/// Implementations will need to implement [allCandidates] to define the total
/// possible search space and [findInCandidates] to define the requirements of
/// the finder.
///
/// This library contains [Finder] and [SemanticsFinder] for searching
/// Flutter's element and semantics trees respectively.
///
/// If the search can be represented as a predicate, then consider using
/// [MatchFinderMixin] along with the [Finder] or [SemanticsFinder] base class.
///
/// If the search further filters the results from another finder, consider using
/// [ChainedFinderMixin] along with the [Finder] or [SemanticsFinder] base class.
abstract class FinderBase<CandidateType> {
bool _cached = false;
/// The results of the latest [evaluate] or [tryEvaluate] call.
///
/// Unlike [evaluate] and [tryEvaluate], [found] will not re-execute the
/// search for this finder. Either [evaluate] or [tryEvaluate] must be called
/// before accessing [found].
FinderResult<CandidateType> get found {
assert(
_found != null,
'No results have been found yet. '
'Either `evaluate` or `tryEvaluate` must be called before accessing `found`',
);
return _found!;
}
FinderResult<CandidateType>? _found;
/// Whether or not this finder has any results in [found].
bool get hasFound => _found != null;
/// Describes zero, one, or more candidates that match the requirements of a
/// finder.
///
/// {@template flutter_test.finders.FinderBase.describeMatch}
/// The description returned should be a brief English phrase describing a
/// matching candidate with the proper plural form. As an example for a string
/// finder that is looking for strings starting with "hello":
///
/// ```dart
/// String describeMatch(Plurality plurality) {
/// return switch (plurality) {
/// Plurality.zero || Plurality.many => 'strings starting with "hello"',
/// Plurality.one => 'string starting with "hello"',
/// };
/// }
/// ```
/// {@endtemplate}
///
/// This will be used both to describe a finder and the results of searching
/// with that finder.
///
/// See also:
///
/// * [FinderBase.toString] where this is used to fully describe the finder
/// * [FinderResult.toString] where this is used to provide context to the
/// results of a search
String describeMatch(Plurality plurality);
/// Returns all of the items that will be considered by this finder.
@protected
Iterable<CandidateType> get allCandidates;
/// Returns a variant of this finder that only matches the first item
/// found by this finder.
FinderBase<CandidateType> get first => _FirstFinder<CandidateType>(this);
/// Returns a variant of this finder that only matches the last item