Home > Blockchain >  how flutter's find() finds widget on widget testing?
how flutter's find() finds widget on widget testing?

Time:12-12

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?

CodePudding user response:

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:

final myText = Text(
  'Hello World',
  key: Key('my_text'),
);

Then, you can use the find.byWidget() method to find this widget in the widget tree, like this:

final foundWidget = find.byWidget(myText);

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.

CodePudding user response:

going inside Flutter's source code, we will find that the find.byWidget() is implemented like this:

  Finder byWidget(Widget widget, { bool skipOffstage = true }) => _WidgetFinder(widget, skipOffstage: skipOffstage);

going more inside _WidgetFinder:

class _WidgetFinder extends MatchFinder {
  _WidgetFinder(this.widget, { super.skipOffstage });

  final Widget widget;

  @override
  String get description => 'the given widget ($widget)';

  @override
  bool matches(Element candidate) {
    return candidate.widget == widget;
  }
}

so for flutter to find a specific widget, it compares it with the == operator with the one you provided.

  • Related