Flutter: No MediaQuery widget ancestor found

8,778

Solution 1

Try creating another widget like this

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

Then your main method will looks like this

void main() {
  runApp(MyApp());
}

Solution 2

Wrap your classname with MaterialApp and your issue is solved. Ex. here my classname is sahim and that's how i solved this issue.

 void main() {
  runApp(
    MaterialApp(
      home: sahim(),
    ),
  );
}

Solution 3

Just do it as below. I have solved it in this way

void main() {
  runApp(MaterialApp(home: Calculator()));
}
Share:
8,778
Simon2215
Author by

Simon2215

Updated on December 26, 2022

Comments

  • Simon2215
    Simon2215 over 1 year
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(Calculator());
    }
    
    class Calculator extends StatelessWidget {
      final numpad_background_color = Color(0x212121);
      final background_color = Colors.black;
      final equal_button_background_color = Color(0xffbe00);
    
      final textColor = Colors.white;
      final operatorTextColor = Color(0xf3ba0e);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                appBar: appbar(context),
                body: Stack(
                  children: [Container(height: MediaQuery.of(context).size.height * 0.37), numpad(context)],
                )));
      }
    
      Widget appbar(BuildContext context) {
        return AppBar(title: Text("Rechner", style: TextStyle(color: textColor, fontSize: 15)), backgroundColor: background_color, leading: Icon(Icons.history));
      }
    
      Widget numpad(BuildContext context) {
        return Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(5), color: numpad_background_color), child:
          Column(children: [
    
          ],),);
      }
    }
    

    Error: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). 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.

    I don't understand the error, I created a MaterialApp Widget and call MediaQuery from there, why does this error appear?

  • Simon2215
    Simon2215 over 3 years
    I tried, but it changed nothing. My code is now like this: pastebin.com/yBw6K8gc
  • Simon2215
    Simon2215 over 3 years
    Sorry, it work's now, it was my mistake. You're my hero, thank you very much! I removed the MaterialApp Widget from Calculator and replaced it with a Scaffold :)
  • Simon2215
    Simon2215 over 3 years
    I'll do that, but I have to wait three more minutes...