8

I'm trying to build a Container that is a third of size of the page but i'm getting an error No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). and I'm not sure why at all. Its in MaterialApp.

My Code:

import 'package:flutter/material.dart';


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

class LoginPage extends StatelessWidget{

  @override
  Widget build(BuildContext context){
    return MaterialApp(
      home: Scaffold(
        body: Container(
          constraints: BoxConstraints.expand(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                color: Colors.red,
                width: double.infinity,
                height: MediaQuery.of(context).size.height/3,
              )
            ],
          )
        )
      )
    );
  }
}
STOPIMACODER
  • 822
  • 2
  • 7
  • 19

4 Answers4

17

You just have to give the MaterialApp as the ancestor..as the error says..

Do it like this..

void main() => runApp(MaterialApp(home:LoginPage()));
srikanth7785
  • 1,382
  • 1
  • 7
  • 22
5

Your must have a MaterialApp widget because you are using the Material class from your import statement

Check the code below, it works fine:

import 'package:flutter/material.dart';

// wrap your LoginPage widget with a MaterialApp widget
void main() => runApp(MaterialApp(home:LoginPage()));

class LoginPage extends StatelessWidget{

  @override
  Widget build(BuildContext context){
    return MaterialApp(
      home: Scaffold(
        body: Container(
          constraints: BoxConstraints.expand(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                color: Colors.red,
                width: double.infinity,
                height: MediaQuery.of(context).size.height/3,
              )
            ],
          )
        )
      )
    );
  }
}
void
  • 12,787
  • 3
  • 28
  • 42
2

None of the solutions worked for me. It was because the showModalBottomSheet tries to access the ancestor of type MaterialApp from the given context.

Use Builder widget to get new context with MaterialApp ancestor

OR

Separate your MaterialAapp and Scaffold widgets into separate widgets.

My solution using Builder :

floatingActionButton: Builder(
  builder: (context) => FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () { showModalBottomSheet(
          context: context,
          builder: (context) {
            return Text('Modal bottom sheet', style: TextStyle(fontSize: 30));
          });
      }
  ),
),
CodingEra
  • 1,313
  • 10
  • 20
0

to add to this, there are cases where the generated test case is not updated to match your current main class enter image description here

elfin
  • 11
  • 1
  • 7