Reputation: 2771
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
?
Upvotes: 16
Views: 3411
Reputation: 169
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
.
Upvotes: 6