是否可以在Flutter测试中从给定的窗口小部件访问子窗口/父窗口小部件?

时间:2017-11-14 22:10:35

标签: dart flutter flutter-test

我正在为Flutter编写单元和集成测试。是否可以从给定的小部件访问子/父窗口小部件?

3 个答案:

答案 0 :(得分:8)

是的,您可以使用find.descendantElement.ancestorWidgetOfExactType

示例:

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

答案 1 :(得分:2)

ancestorWidgetOfExactType已弃用,建议使用findAncestorWidgetOfExactType

答案 2 :(得分:0)

// 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文档-descendantancestor