Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a BuildContext from WidgetTester?

Tags:

flutter-test

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?

like image 797
buttonsrtoys Avatar asked Jan 19 '26 14:01

buttonsrtoys


1 Answers

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.

like image 55
Mohd Khalil Ur Rehman Avatar answered Jan 21 '26 06:01

Mohd Khalil Ur Rehman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!