错误代码
// ignore: must_be_immutable
class CustomButton extends StatelessWidget {
CustomButton({this.label});
String label;
@override
Widget build(BuildContext context) {
return new RaisedButton(onPressed: () {},
child: new Text(label, textDirection: TextDirection.ltr,));
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(appBar: new AppBar(title: new Text("demo"),),
body: new CustomButton(label: "hello"));
}
}
void main() {
runApp(new MyButton());
}
日志
09-19 11:29:07.530 13216-13272/com.flutter.flutter_app I/flutter: The following assertion was thrown building MyButton:
09-19 11:29:07.530 13216-13272/com.flutter.flutter_app I/flutter: MediaQuery.of() called with a context that does not contain a MediaQuery.
09-19 11:29:07.530 13216-13272/com.flutter.flutter_app I/flutter: No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
09-19 11:29:07.530 13216-13272/com.flutter.flutter_app I/flutter: This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
09-19 11:29:07.530 13216-13272/com.flutter.flutter_app I/flutter: a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
分析
因为这里我们使用了RaisedButton是一个Material的组件 所以用Scaffold包裹,包裹后直接返回给MyButton,这里就会报错,日志中说到
This can happen because you do not have a WidgetsApp or MaterialApp widget
说明这个Scaffold必须使用MaterialApp进行包裹,所以修改代码
正确代码
// ignore: must_be_immutable
class CustomButton extends StatelessWidget {
CustomButton({this.label});
String label;
@override
Widget build(BuildContext context) {
return new RaisedButton(onPressed: () {},
child: new Text(label, textDirection: TextDirection.ltr,));
}
}
//因为RaisedButton是一个Material的组件 所以用Scaffold包裹 ,但是最外层必须返回一个MaterialApp
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(home: new Scaffold(appBar: new AppBar(title: new Text("demo"),),
body: new CustomButton(label: "hello")));
}
}
void main() {
runApp(new MyButton());
}