I’m learning flutter’s widget testing
and I’m reading flutter’s official documentation of widget testing.
I wonder how find() method finds the widget.
find.byKey() may find by look around widget tree that which widget has specific key,
but like find.byWidget() how does it finds specific widget?
2
Answers
The find.byWidget() method finds a widget by checking if it is equal to the widget passed as an argument to the method. This is typically done by checking if the runtimeType and key of the two widgets match.
For example, let’s say you have a Text widget with a specific key and you want to find it using the find.byWidget() method. You would first create the Text widget and assign it a key, like so:
Then, you can use the find.byWidget() method to find this widget in the widget tree, like this:
This will return the Text widget if it is found in the widget tree, or null if it is not found. You can then use this widget reference to perform assertions or interact with the widget in your tests.
Keep in mind that the find.byWidget() method only checks for strict equality between the two widgets. This means that if you have multiple widgets with the same runtimeType and key, the find.byWidget() method will only return the first widget it encounters that matches the criteria. To find all widgets that match the criteria, you can use the find.descendant() method instead.
going inside Flutter’s source code, we will find that the
find.byWidget()
is implemented like this:going more inside
_WidgetFinder
:so for flutter to find a specific widget, it compares it with the
==
operator with the one you provided.