本文介绍了Flutter:如何使用DropDownMenuItems导航到新屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我选择MEN时,我希望能够导航到一个新屏幕,而当选择WOMEN时,我希望能够导航至另一个屏幕。
我尝试过,似乎没有任何运气。网上似乎没有任何东西。
请问我该怎么做?
I want to be able to navigate to a new screen when I choose MEN and another screen when I choose WOMEN.I've tried and did not seem to have any luck. There seems to be nothing on this on the web.Please how d I do this?
这是我的代码:
return Scaffold(
appBar: AppBar(
title: DropdownButtonHideUnderline(
child: new DropdownButton(
value: null, //Have no idea what to put here
items: <DropdownMenuItem>[
new DropdownMenuItem(
child: new Text('MEN', style: style),
),
new DropdownMenuItem(
child: new Text('WOMEN', style: style),
),
],
onChanged: null,
),
),
),
);
推荐答案
首先,您应该在DropDownMenuItem中添加值
First you should add value in DropDownMenuItem as
new DropdownMenuItem(
value: "MEN",
child: new Text('MEN', style: style),
),
然后在onChanged内部,您应该检查值并管理导航。
Then inside onChanged you should check value and manage navigation.
return Scaffold(
appBar: AppBar(
title: DropdownButtonHideUnderline(
child: new DropdownButton(
value: "MEN", //Default value
items: <DropdownMenuItem>[
new DropdownMenuItem(
value: "MEN",
child: new Text('MEN', style: style),
),
new DropdownMenuItem(
value: "WOMEN",
child: new Text('WOMEN', style: style),
),
],
onChanged: (v) {
Widget widget;
if (v == "MEN") {
widget = new MenWidget();
} else if (v == "WOMEN") {
widget = new WomenWidget();
}
Navigator.push(
context,
MaterialPageRoute(builder: (context) => widget),
);
},
),
),
),
);
根据评论进行更新
要根据选择更新正文,应使用StatefulWidget。
To update body according to selection, you should use StatefulWidget.
class DropDownButtonScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _DropDownButtonScreenState();
}
}
class _DropDownButtonScreenState extends State<DropDownButtonScreen> {
String ddValue;
@override
void initState() {
super.initState();
ddValue = "MEN";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: DropdownButtonHideUnderline(
child: new DropdownButton(
value: ddValue, //Default value
items: <DropdownMenuItem>[
new DropdownMenuItem(
value: "MEN",
child: new Text('MEN'),
),
new DropdownMenuItem(
value: "WOMEN",
child: new Text('WOMEN'),
),
],
onChanged: (v) {
ddValue = v;
setState(() {});
},
),
),
),
body: getBody(),
);
}
Widget getBody() {
if (ddValue == "MEN") {
return Center(child: Text("Widget for men"));
} else if (ddValue == "WOMEN") {
return Center(child: Text("Widget for Women"));
}
return Center(child: Text("Widget not found"));
}
}
这篇关于Flutter:如何使用DropDownMenuItems导航到新屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!