Flutter Error: MediaQuery.of() called with a conte

2020-02-10 10:39发布

I have been trying to get the size of the whole context view in Flutter. But every time I try I'm getting the above mentioned error. Here's my code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    return new MaterialApp(
      home: new Scaffold(),
    );
  }
}

Note: I also tried with a StatefulWidget. Please, help me find what I'm doing wrong here.

标签: dart flutter
9条回答
【Aperson】
2楼-- · 2020-02-10 11:35

I fixed it by using the following method. First I created a new class named MyWidget and returned it in MyApp within a MaterialApp's home:. Refer code below:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return new MaterialApp(
      home: new MyWidget(),
    );
  }
} 

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    return new MaterialApp(
      home: new Scaffold(),
    );
  }
} 

Also, declaring size as final doesn't matter. Orientation/Rotation is handled.

查看更多
在下西门庆
3楼-- · 2020-02-10 11:37

Had the same error in

import 'screens/tasks_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TasksScreen();

  }
}

I solved it by:-

import 'package:flutter/material.dart';
import 'screens/tasks_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TasksScreen(),
    );
  }
}
查看更多
一夜七次
4楼-- · 2020-02-10 11:41

Wrap your code in a Material App widget. I also had the same issue as I forgot to use it and directly returned the scaffold.

In other words, your MediaQuery.of(context) should be inside the Material Widget. Material app -> scaffold -> MediaQuery.of(context)

查看更多
登录 后发表回答