Reputation: 518
I am getting an error saying No MediaQuery widget ancestor found while using MediaQuery.of(context). Here is my code and I am using MediaQuery.of(context) inside a MaterialApp but it is still giving me errors. Can someone help?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Responsive'),
),
body: SingleChildScrollView(
child: Column(
children: [
Container(
color: Colors.red,
height: mediaQuery.size.height,
),
Container(
color: Colors.amber,
height: 200,
),
],
),
),
),
);
}
}
Error
Upvotes: 1
Views: 791
Reputation: 1865
You get this error because your MediaQuery
is out of MaterialApp
. Use material home as seperate Stateless of Statefull widget.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return MaterialApp(
home: Home();
}
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return Scaffold(
appBar: AppBar(
title: Text('Responsive'),
),
body: SingleChildScrollView(
child: Column(
children: [
Container(
color: Colors.red,
height: mediaQuery.size.height,
),
Container(
color: Colors.amber,
height: 200,
),
],
),
),
);
}
}
Upvotes: 1
Reputation: 661
you need to use media Query like that
Size size = MediaQuery.of(context).size;
and where you want to use so like this according width or height
height: size.height*0.1,
Upvotes: 0