Reputation: 120489
I'm writing unit and integration tests for Flutter. Is it possible to access children/parent widgets from a given widget?
Upvotes: 45
Views: 26454
Reputation: 3189
Yes, you can use find.descendant
and Element.findAncestorWidgetOfExactType
.
Examples:
// Finds a RichText widget that a descendant (child/grand-child/etc) of a
// tab widget with text "Tab 1"
find.descendant(of: find.text('Tab 1'), matching: find.byType(RichText));
// Finds a parent widget of type MyParentWidget.
tester.element(find.byType(MyChildWidget))
.findAncestorWidgetOfExactType(MyParentWidget);
Upvotes: 59
Reputation: 2114
// Parent with a child & grand child
class ParentWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChildWidget(
child: GrandChildWidget(),
);
}
}
// Tests
void main() {
testWidgets('parent, child & grand-child hierarchy', (WidgetTester tester) async {
Widget parentWidget = ParentWidget();
await tester.pumpWidget(parentWidget);
final childFinder = find.descendant(of: find.byWidget(parentWidget), matching: find.byType(ChildWidget));
expect(childFinder, findsOneWidget);
final grandChildFinder = find.descendant(of: find.byWidget(parentWidget), matching: find.byType(GrandChildWidget));
expect(grandChildFinder, findsOneWidget);
final parentFinder = find.ancestor(of: find.byWidget(childWidget), matching: find.byType(ParentWidget));
expect(parentFinder, findsOneWidget);
});
}
Flutter docs - descendant & ancestor
Upvotes: 8
Reputation: 76
ancestorWidgetOfExactType is deprecated, prefer using findAncestorWidgetOfExactType
Upvotes: 5