Add a MediaQuery Widget
- Wrap your widget that requires media query properties with a
MediaQuery widget if your widget is not being wrapped by the app’s MaterialApp or CupertinoApp. This widget provides information about the size and orientation of the current device, which typically is provided automatically by these app wrapper widgets.
- For instance, if you're rendering widgets directly without an app wrapper, you can do this:
void main() {
runApp(
MediaQuery(
data: MediaQueryData(),
child: MyApp(),
),
);
}
Ensure MaterialApp or CupertinoApp is Used
- Ensure that your main app widget tree starts with either
MaterialApp or CupertinoApp. These widgets automatically create a MediaQuery accessible to all widgets beneath them.
- If not present, adjust your main function like this:
void main() {
runApp(MaterialApp(
home: MyHomePage(),
));
}
Use of Builder Widget
- When you’re using widgets that consume the
BuildContext directly, such as Scaffold or AppBar, and you need access to MediaQuery immediately, employ a Builder widget to provide a new context.
- Example usage:
Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Builder(
builder: (context) {
var mediaQuery = MediaQuery.of(context);
return Center(
child: Text('Width: ${mediaQuery.size.width}'),
);
},
),
);
Verification in Widget Tests
- If you encounter this error during widget testing, make sure
MediaQuery is properly set. Often it involves wrapping your widget under test with MaterialApp during the test widget creation.
- Example test setup:
testWidgets('Widget has no MediaQuery', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: TestedWidget(),
),
);
// Perform your test assertions here
});
Adjust Widgets with Context Requirement
- Some widgets are dependent on context initialized with a
MediaQuery. Ensure you position such widgets (e.g., Dialogs, BottomSheets) within the widget tree that has a MediaQuery.
- If implementing a custom widget, ensure it makes a call to the correct
BuildContext :
class CustomWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
var mediaQuery = MediaQuery.of(context);
return Container(
width: mediaQuery.size.width / 2,
height: mediaQuery.size.height / 3,
);
}
}
By following these solutions, you can ensure that your Flutter app is setup to properly utilize media queries wherever needed, avoiding the "No MediaQuery widget found" exception.