Why This Happens
In Flutter, MediaQuery.of(context) requires a MediaQuery ancestor in the widget tree, which is automatically provided by MaterialApp or WidgetsApp. If you call it outside these widgets or in a test without proper setup, this error occurs.
The Problem
void main() {
runApp(
Builder(
builder: (context) {
final size = MediaQuery.of(context).size; // No MediaQuery!
return Text('$size');
},
),
);
}The Fix
void main() {
runApp(
MaterialApp(
home: Builder(
builder: (context) {
final size = MediaQuery.of(context).size;
return Text('$size');
},
),
),
);
}Step-by-Step Fix
- 1
Identify the error
Look at the error message: No MediaQuery widget ancestor found. This means MediaQuery.of was called without a proper app widget ancestor.
- 2
Find the cause
Check if the widget using MediaQuery.of is placed outside of MaterialApp/WidgetsApp, or if the test is missing a MediaQuery wrapper.
- 3
Apply the fix
Ensure the widget is inside MaterialApp, or wrap it in a MediaQuery widget for testing.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free