我正在为 Flutter 编写单元和集成测试。是否可以从给定的小部件访问子/父小部件?
问问题
15604 次
3 回答
41
是的,您可以使用find.descendant
和Element.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);
于 2017-11-14T22:24:11.850 回答
5
不推荐使用祖先WidgetOfExactType,更喜欢使用findAncestorWidgetOfExactType
于 2020-03-30T19:14:16.977 回答
2
// 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);
});
}
于 2020-11-03T05:20:36.293 回答