Flutter - how to get widget count on integration test

Viewed 1814

how can i get the widget count

final SerializableFinder finder = find.byType('MyWidget');
await driver.tap(finder);

but MyWidget may be more than one,
that will throw exception

2 Answers

You will need to use some attribute that allows you to find the widget you need. For example, add a Key to each of these widgets, so it's easier to find the one you need:

...MyWidget(key: Key('myWidget1'))...

So, find it by key:

find.byKey(Key('myWidget1'))

If you want to find the widget count, you can use this:

final finder = find.byType(MyWidget, skipOffstage: false); // Without quotes!
final count = tester.widgetList<MyWidget>(finder).length;

If you want to find one or more widgets matching yours, use findsWidgets :

final SerializableFinder finder = find.byType('MyWidget');
expect(finder, findsWidgets);

If you're looking for an exact number of widgets, you can count how many matching nodes are in the widget tree using findsNWidgets() (let's say 4):

final SerializableFinder finder = find.byType('MyWidget');
expect(finder, findsNWidgets(4));
Related