DEV Community

Jan Mewes
Jan Mewes

Posted on โ€ข Edited on

3 3

Built-in Flutter Widget Finders

This blog post provides an overview of the options for querying widgets in widget tests which are available by default in the flutter_test library.


Table of contents


Identifier

Find by key

find.byKey(const ValueKey('continue'))
Enter fullscreen mode Exit fullscreen mode

Text

Find by text

find.text('Back')
Enter fullscreen mode Exit fullscreen mode

Find by rich text

find.text('Close', findRichText: true)
Enter fullscreen mode Exit fullscreen mode

Find by partial text

find.textContain('Back')
Enter fullscreen mode Exit fullscreen mode

Find by matching text

find.textContain(RegExp(r'(\w+)'))
Enter fullscreen mode Exit fullscreen mode

Type

Find by class name

find.byType(IconButton)
Enter fullscreen mode Exit fullscreen mode

Find by icon

find.byIcon(Icons.inbox)
Enter fullscreen mode Exit fullscreen mode

Find by element type

find.byElementType(SingleChildRenderObjectElement)
Enter fullscreen mode Exit fullscreen mode

Hierarchy

Find by descendant

find.descendant(
  of: find.byType(TextField),
  matching: find.text('Key 1'),
)
Enter fullscreen mode Exit fullscreen mode

Find by ancestor

find.ancestor(
  of: find.text('faded'),
  matching: find.byType('Opacity'),
)
Enter fullscreen mode Exit fullscreen mode

Miscellaneous

Find by semantics label

find.bySemanticsLabel('Back')
Enter fullscreen mode Exit fullscreen mode

Find by image

find.image(FileImage(File(filePath)))
Enter fullscreen mode Exit fullscreen mode

Find by tooltip

find.byTooltip('Back')
Enter fullscreen mode Exit fullscreen mode

Find by widget predicate

find.byWidgetPredicate(
 (Widget widget) => widget is Tooltip && widget.message == 'Back',
 description: 'widget with tooltip "Back"',
)
Enter fullscreen mode Exit fullscreen mode

Find by element predicate

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',
)
Enter fullscreen mode Exit fullscreen mode

References

Credits

The source code snippets are adapted from the examples in the Flutter source code which is licensed under the BSD-3-Clause License.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay