41

I'm writing unit and integration tests for Flutter. Is it possible to access children/parent widgets from a given widget?

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279

3 Answers3

57

Yes, you can use find.descendant and Element.ancestorWidgetOfExactType.

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))
  .ancestorWidgetOfExactType(MyParentWidget);
Yegor
  • 2,931
  • 1
  • 17
  • 6
8
// 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

Srikanth
  • 2,014
  • 19
  • 22
5

ancestorWidgetOfExactType is deprecated, prefer using findAncestorWidgetOfExactType

Josua
  • 76
  • 1
  • 3