我在让Dropdownbutton小部件在Flutter(1.0)中工作时遇到问题,它不断抛出错误,
以下是我的代码:
import 'package:flutter/material.dart';
void main() => runApp(new Myapp());
class Myapp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new Myappstate();
}
}
class Myappstate extends State<Myapp> {
String value = '';
List<String> values = [];
void init() {
values.addAll(['one', 'two']);
value = values.elementAt(0);
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("drop down demo"),
),
body: new Container(
child: new Column(
children: <Widget>[
new DropdownButton(
items: values.map((String val) {
return new DropdownMenuItem(
value: val,
child: Text(val),
);
}).toList(),
onChanged: null,
)
],
),
),
);
}
}
我收到以下错误:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 4352): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 4352): The following assertion was thrown building Myapp(state: Myappstate#1abe5):
I/flutter ( 4352): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter ( 4352): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter ( 4352): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter ( 4352): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter ( 4352): The context used was:
I/flutter ( 4352): Scaffold(dirty, state: ScaffoldState#cda06(lifecycle state: initialized, tickers: tracking 1
I/flutter ( 4352): ticker))
我正在尝试添加这个非常基本的小部件,但是由于某种原因,我未能找到问题所在。
感谢我能找到的任何帮助。
答案 0 :(得分:1)
您必须包装MaterialApp并将初始数据加载到initState中。
请稍作更改检查此代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomeapp(),
);
}
}
class MyHomeapp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyHomeappstate();
}
}
class MyHomeappstate extends State<MyHomeapp> {
String value = '';
List<String> values = [];
@override
void initState() {
super.initState();
setState(() {
values.addAll(['one', 'two']);
value = values.elementAt(0);
});
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("drop down demo"),
),
body: new Container(
child: new Column(
children: <Widget>[
new DropdownButton(
hint: Container(
child: Text('Select option'),
),
items: values.map((String val) {
return new DropdownMenuItem(
value: val,
child: Text(val),
);
}).toList(),
onChanged: (val) {
debugPrint('selected option: $val');
},
)
],
),
),
);
}
}