When doing a Flutter widget test, I can get a context from the WidgetTester if I know something about at least one widget in the tree. E.g., if I know there's a Text widget in the test widget tree, I can
BuildContext context = tester.element(find.byType(Text));
How can I get a context more generally? E.g., can I get the root widget of the tree and get its BuildContext?
Declare a navigatorKey using
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Assign this navigatorKey to your material app widget in your test class.
await tester.pumpWidget(
MaterialApp(
home: const Scaffold(),
navigatorKey: navigatorKey,
),
);
Then you will be able to access its context using navigatorKey.currentContext.
Note that there must be a widget in the tree (in this case a Scaffold) otherwise navigatorKey.currentContext will be null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With