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,
)
],
)
)
)
);
}
}
To solve this No MediaQuery widget found Error You Must have to use MaterialApp() to use MediaQuery. You cant use MediaQuery without MaterialApp Widget To use MediaQuery. of() function, first, you need to wrap your widget with MaterialApp(), even after that, you may get the error.
MaterialApp Class: MaterialApp is a predefined class in a flutter. It is likely the main or core component of flutter. We can access all the other components and widgets provided by Flutter SDK.
You just have to give the MaterialApp
as the ancestor..as the error says..
Do it like this..
void main() => runApp(MaterialApp(home:LoginPage()));
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,
)
],
)
)
)
);
}
}
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));
});
}
),
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With