dartflutterflutter-test

Is it possible to access children/parent widgets from a given widget, in a Flutter test?


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


Solution

  • 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);