How to Solve ’No MediaQuery widget found’ Error in Flutter

Are you getting 'No MediaQuery widget found' error exception while using MediaQuery class in your Flutter App then see the explanation below to solve this issue. This error only appears when you use MediaQuery class but you haven't positioned MaterialApp() widget correctly. 

The error may look like this:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════
No MediaQuery widget ancestor found.
MyApp widgets require a MediaQuery widget ancestor.
The specific widget that could not find a MediaQuery ancestor was:
  MyApp
The ownership chain for the affected widget is: "MyApp ← [root]"

To use MediaQuery.of() function, first, you need to wrap your widget with MaterialApp(), even after that, you may get the error. To solve this error fully, you need to place MaterialApp() widget like below:

import 'package:flutter/material.dart';
void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp( //use MaterialApp() widget like this
      home: Home() //create new widget class for this 'home' to 
                   // escape 'No MediaQuery widget found' error
    );
  }
}

//create new class for "home" property of MaterialApp()
class Home extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return Scaffold(
          body: Container( 
                //MediaQuery methods in use
                 width: MediaQuery.of(context).size.width,
                 height: MediaQuery.of(context).size.height * 0.4, 
             )
       );
  }
}

Here, we have used MediaQuery.of() function inside MaterialApp() widget, and we have created a different class for home attribute of MeterialApp(). 

In this way, you can solve 'No MediaQuery widget found' error in Flutter App.

No any Comments on this Article


Please Wait...