|

|  No MediaQuery widget found in Flutter: Causes and How to Fix

No MediaQuery widget found in Flutter: Causes and How to Fix

February 10, 2025

Discover causes and solutions for the "No MediaQuery widget found" error in Flutter. Fix your layout issues with our comprehensive step-by-step guide.

What is No MediaQuery widget found Error in Flutter

 

No MediaQuery Widget Found Error in Flutter

 

The "No MediaQuery widget found" error in Flutter signifies that a widget attempting to access the MediaQuery context cannot find one. This typically occurs when a widget that relies on MediaQuery.of(context) is not wrapped within a widget tree that includes a MediaQuery widget, such as MaterialApp or WidgetsApp. The MediaQuery widget is crucial as it provides information about the device's screen size, orientation, and other properties related to the display.

 

Understanding the Context

 

  • Widgets like `MediaQuery.of(context).size` or others using `MediaQuery` require context that must be wrapped by widgets providing screen properties.
  •  

  • Flutter automatically inserts a `MediaQuery` widget when using Material Design widgets, but when non-material widgets are used, it might not be present.

 

Code Example: Proper Structure

 

To understand where the error might occur, you can look at a typical structure that leads to this error versus a correct implementation.

 

// Incorrect Example: This will cause "No MediaQuery widget found" error
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Trying to access MediaQuery here will fail
    final Size screenSize = MediaQuery.of(context).size;
    
    return Container(
      child: Text('Screen size: $screenSize'), 
    );
  }
}

 

In the above example, MediaQuery.of(context).size fails because context is not under a valid MediaQuery subtree.

 

Correct Example: Including MaterialApp

 

// Correct Example: Wrapping in MaterialApp
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(title: Text('Demo')),
      body: Center(
        child: Text('Screen size: $screenSize'),
      ),
    );
  }
}

 

This example demonstrates the correct usage with MaterialApp providing a structure for MediaQuery. The HomeScreen widget can safely access MediaQuery.of(context) because MaterialApp ensures that MediaQuery is available.

 

Common Usage Scenarios

 

  • Obtaining screen size for responsive designs.
  •  

  • Adapting layouts in different screen orientations.
  •  

  • Accessing padding for devices with notches or rounded corners.

 

Understanding the "No MediaQuery widget found" error is essential for developers when building responsive UIs in Flutter, ensuring that all widgets are properly wrapped within the appropriate contexts provided by Flutter's widget tree.

What Causes No MediaQuery widget found in Flutter

 

Overview of the "No MediaQuery Widget Found" Issue

 

  • Widget Hierarchical Structure: The error often arises because a widget that depends on the MediaQuery context is placed outside the boundaries of where a MediaQuery widget is accessible. In Flutter, MediaQuery is typically introduced to the widget tree by the MaterialApp, CupertinoApp, or WidgetsApp class, which wraps around widgets like Scaffold, AppBar, and others. If a widget that requires MediaQuery is initialized outside these contexts, it will not have access to the MediaQuery data, hence the error.
  •  

  • Improper Widget Placement: A common cause is placing a widget that depends on device size or orientation outside the scope of widgets that provide MediaQuery data. For example, attempting to build a widget that uses MediaQuery during the initialization of a global or top-level widget without it being wrapped in MaterialApp or similar can lead to this issue.
  •  

  • Widget Initialization Order: Sometimes developers try to fetch MediaQuery data during a widget's construction phase (in the constructor or variable initialization). At this point, the widget might not yet be in the widget tree or have access to a BuildContext with a MediaQuery ancestor.

 

Common Scenarios Triggering the Error

 

  • Directly Using MediaQuery in Stateless or Stateful Widgets: If a StatelessWidget or StatefulWidget tries to access MediaQuery.of(context) in its constructor or during state initialization, this may cause the error because, at this point, the widget is not fully part of the widget tree with MaterialApp or equivalent above it.
  •  

  • Custom Widgets or External Libraries: When using custom widgets or third-party library widgets expecting a MediaQuery context, if these widgets are not placed inside a tree with the appropriate root-level wrapper that introduces MediaQuery, the error is likely to occur.
  •  

  • Dialog and Overlay Usage: Using MediaQuery in dialogs or overlays without ensuring these elements are appropriately wrapped may also lead to errors since they might not automatically be wrapped in MediaQuery context in certain setups.

 

Code Example Illustrating Potential Error Scenario

 

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Incorrect usage: MediaQuery used before MaterialApp is in the widget tree.
    final screenHeight = MediaQuery.of(context).size.height; // Causes exception

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MediaQuery Example'),
        ),
        body: Center(
          child: Text('Screen Height: $screenHeight'),
        ),
      ),
    );
  }
}

 

In this code snippet, the MediaQuery.of(context).size.height is called before MaterialApp is in the widget tree, resulting in the "No MediaQuery widget found" exception. This illustrates the need for correct widget placement and initialization to ensure MediaQuery is available.

 

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

How to Fix No MediaQuery widget found in Flutter

 

Wrap with a MaterialApp or WidgetsApp

 

  • Ensure that your widget tree is wrapped with a MaterialApp or WidgetsApp. These widgets provide the necessary MediaQuery data.

 

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

 

Use Builder or LayoutBuilder

 

  • When defining a widget within a build() method, it's sometimes necessary to ensure that widgets accessing the MediaQuery are within the context. Use a Builder to create a new context.

 

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (context) {
          var mediaQuery = MediaQuery.of(context);
          return Center(
            child: Text(
              'Width: ${mediaQuery.size.width}',
            ),
          );
        },
      ),
    );
  }
}

 

Ensure Context is Correct

 

  • Always check that the context you are using is correct and comes after the MaterialApp in the widget tree. Any widget trying to access MediaQuery should not be higher in the hierarchy than the MaterialApp.
  •  

  • Use a separate MaterialApp for any independent widget trees.

 

Check for Descendants

 

  • If your widget might be placed within a subtree that does not have a MediaQuery, explicitly check and ensure that it is inserted into the app's main widget structure where a MaterialApp or CupertionApp exists.

 

Error Handling

 

  • Implement error handling to catch exceptions where MediaQuery dependence might cause a failure and proceed with a fallback or default screen size.

 

Widget safeMediaQuery(BuildContext context) {
  try {
    final mediaQuery = MediaQuery.of(context);
    return MyWidget(mediaQuery: mediaQuery);
  } catch (e) {
    // Fallback to a default size
    return MyWidget(mediaQuery: MediaQueryData(size: Size(300, 600)));
  }
}

 

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Speak, Transcribe, Summarize conversations with an omi AI necklace. It gives you action items, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

  • Real-time conversation transcription and processing.
  • Action items, summaries and memories
  • Thousands of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Vision

Compliance

Products

Omi

Omi Apps

Omi Dev Kit 2

omiGPT

Personas

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

© 2025 Based Hardware. All rights reserved.