I'm trying to set a drawer size dynamically.
import 'package:flutter/material.dart';
import './screens/tab_screen.dart';
//widgets
import './widgets/main_drawer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: TabWidget(),
endDrawer: Container(
width: MediaQuery.of(context).size.width * 0.65,
child: MainDrawer(),
),
),
title: "Ali Azad",
// routes: {
// '/': (_) => TabWidget(),
// },
);
}
}
but I have got this error = MediaQuery.of() called with a context that does not contain a MediaQuery.;
If you take a look better in your code, you will see that your build method is called with a context and by the time of that call, there isn't any previous Widget, which mean that your MaterialApp doesn't exist yet when your build is called, so that BuildContext doesn't have any previous MaterialApp, you can solve this just by splitting your code like this:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
title: "Ali Azad",
);
}
}
// This Home Widget will be a child of MaterialApp, and the BuildContext has access to this Material widget.
class Home extends StatelessWidget{
@override
Widget build(BuildContext context){
return Scaffold(
body: TabWidget(),
endDrawer: Container(
width: MediaQuery.of(context).size.width * 0.65,
child: MainDrawer(),
)
);
}
}
Or if you don't want to create another Widget, then you should use a Builder widget that will generate a new BuildContext for you. Your Widget would look like this:
MaterialApp(
home: Builder(
build: (BuildContext context) {
return Scaffold(
body: TabWidget(),
endDrawer: Container(
width: MediaQuery.of(context).size.width * 0.65,
child: MainDrawer(),
)
);
}
),
title: "Ali Azad",
);
put your Container
widget inside a Builder
widget or create a separate widget an assign it to MaterialApp
home
parameter, this way you get the context
of MaterialApp
widget, the context
you are now using doesn't have a MaterialApp
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.