0
votes

The code below throws the exception:

I/flutter (23313): The following assertion was thrown building MyApp(dirty): I/flutter (23313): MediaQuery.of() called with a context that does not contain a MediaQuery. I/flutter (23313): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). I/flutter (23313): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce I/flutter (23313): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.

I dont know what is the cause of the error is thrown because the Widget ancestor of the Container is a MaterialApp widget.

Could you help me please?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body:Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                child:Text("Hello")
            )
        )
    );
  }
}
2

2 Answers

0
votes

You cannot use MediaQuery or anything that requires a context like Theme.of before you build your MaterialApp.

You should do this instead.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light.copyWith(
      statusBarBrightness: Brightness.light,
    ));
    return MaterialApp(
        home: Home()
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body:Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child:Text("Hello")
        )
    );
  }
}
0
votes

Try it like this:

import 'package:flutter/material.dart';

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

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          body: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Text("Hello"))),
    );
  }
}