Outline
When you write the test code on Flutter, sometimes you need to find the parent widget or child widget for the test.
In this blog post, I will introduce how to find the parent widget or child widget and check the values of them in the test code.
You can see the full source code of the blog post in GitHub
.
Prepare project
To see how to find the parent widget or child widget in the test code, execute the following command to create a new Flutter project.
flutter create find_child_and_parent_widget
In this blog post, I will use the basic app, that is created when the flutter create
command is executed, to access the parent widget or child widget.
Find parent widget
To find the parent widget in the test code, you can use findAncestorWidgetOfExactType
. Open the test/widget_test.dart
file and modify it like the following to see how to find the parent widget.
testWidgets('Find parent widget', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
final column = tester
.element(find.text('You have pushed the button this many times:'))
.findAncestorWidgetOfExactType<Column>();
expect((column?.children[1] as Text).data, '0');
});
This test code is to find an element has the You have pushed the button this many times:
text, and find the closest parent Column
widget via the findAncestorWidgetOfExactType
function.
And then, it checks the child Text
widget has the text correctly. After modifying the test code, execute the following command to execute the test code.
flutter test test/widget_test.dart
Then, you can see the test code works well like the following.
00:04 +1: All tests passed!
Find child widget
You can use descendant
to find the child widget in the test code. To see how to find the child widget, open thetest/widget_test.dart
file and modify it like the below.
testWidgets('Find child widget', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
final icon = find.descendant(
of: find.byType(Scaffold),
matching: find.byType(Icon),
);
expect(tester.widget<Icon>(icon).icon, Icons.add);
});
This code is to find the Icon
type child widget from the Scaffold
widget, and check the widget’s icon is the add
icon. After modifying the code, execute the following command to execute the test code.
flutter test test/widget_test.dart
And then, you can see the test code works well like the following.
00:03 +2: All tests passed!
Completed
Done! we’ve seen how to find the parent widget or child widget in the test code on Flutter. Sometimes we need to find the parent or child widget in the test code, so it will be helpful to remember these.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.