Flutter - No MediaQuery Widget Ancestor Found
During the Flutter app development, you may have seen No MediaQuery widget ancestor found. This can happen because you have not added a WidgetsApp, CupertinoApp, or MaterialApp widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
Error Massage:
You can see the below error message when occur No MediaQuery widget ancestor found.
======== Exception caught by widgets library =======================================================
The following assertion was thrown building Scaffold(dirty, state: ScaffoldState#9da29(tickers: tracking 2 tickers)):
No MediaQuery widget ancestor found.
Scaffold widgets require a MediaQuery widget ancestor.
The specific widget that could not find a MediaQuery ancestor was: Scaffold
dirty
state: ScaffoldState#9da29(tickers: tracking 2 tickers)
The ownership chain for the affected widget is: "Scaffold ← Home ← [root]"
Error Code:
You can see below the code where we are not using any WidgetsApp, CupertinoApp, or MaterialApp. We directly used the Home Stateless widget in runApp.
void main() {
runApp(const Home());
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(body: Card(child: Container()));
}
}
Solution:
We can easily solve this error MyApp class, you should wrap it with MaterialApp or CupertinoApp. It should fix the problem. You can see below code:
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp( //Wrap MaterialApp Here
debugShowCheckedModeBanner: false,
title: 'Errorgram',
theme: ThemeData(
// useMaterial3: true,
primarySwatch: Colors.blue,
),
home: const Home(title: 'Flutter Demo Home Page'),
);
}
Run your project now your error is fixed.
Conclusion:
We have seen How to solve the error No MediaQuery widget ancestor found in Flutter. I hope this solution may help you
Copyright 2024 ErrorGram