Testing in flutter gives error MediaQuery.of() called with a context that does not contain a MediaQuery

Issue

I am trying to test the code for the login page in a flutter. This is the first time for me and I am just following the template provided by them. But whatever widget I try to push gives an error saying MediaQuery.of() called with a context that does not contain a MediaQuery.

I have tried out by pumping different widgets in my app. But each and every widget gives the same error as mentioned above, on the other hand, my app is working fine on the device but while testing it gives the error for just pumping the widget.

await tester.pumpWidget(Login());

and Login page is simple Scaffold with appbar and body.

Solution

Add this helper method :

 Widget buildTestableWidget(Widget widget) {
   return MediaQuery(data: MediaQueryData(), child: MaterialApp(home: widget));
 }

Then you can use inside your Test:

 await tester.pumpWidget(buildTestableWidget(Login()));

Answered By – diegoveloper

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *