我已经构建了DropdownMenuItem的代码,现在当我从dropdownmenuitem中单击一个项目时,它应该移到另一个屏幕。下面是代码
class TimesScreen extends StatefulWidget {
@override
_TimesScreenState createState() => _TimesScreenState();
}
class _TimesScreenState extends State<TimesScreen> {
var gender;
@override
Widget build(BuildContext context) {
DropdownButton(
hint: Text("Select",
style: TextStyle(color: Colors.white),),
onChanged: (val){
setState(() {
this.gender=val;
});
},
value: this.gender,
items: [
DropdownMenuItem(
//onTap:
value: 'Earth',
child: Text('Earth'
),
),
DropdownMenuItem(
//onTap:
value: 'Mars',
child: Text('Mars'
),
),)]
答案 0 :(得分:1)
您可以用Text
包装GestureDetector
小部件,该小部件具有一个onTap
函数,可用来执行所需的代码。有关更多详细信息,请参见:https://api.flutter.dev/flutter/widgets/GestureDetector-class.html
这应该有效:
DropdownMenuItem(
value: 'Earth',
child: GestureDetector(
onTap: () {
// navigate code...
},
child: Text('Earth')
),
),
答案 1 :(得分:-1)
在应用fayeed的解决方案之后,我注意到这仅使下拉菜单中的 text 可以单击。要解决此问题,您只需使用DropdownButton.onChanged
。
完整小部件:
class TimesScreen extends StatefulWidget {
@override
_TimesScreenState createState() => _TimesScreenState();
}
class _TimesScreenState extends State<TimesScreen> {
var gender;
@override
Widget build(BuildContext context) {
return DropdownButton(
hint: Text("Select"),
value: this.gender,
items: [
DropdownMenuItem(value: 'Earth', child: Text('Earth')),
DropdownMenuItem(value: 'Mars', child: Text('Mars')),
],
onChanged: (val) {
setState(() {
this.gender = val;
});
switch (val) {
case 'Earth':
Navigator.pushNamed(context, '/earth_target_page');
break;
case 'Mars':
Navigator.pushNamed(context, '/mars_target_page');
break;
}
},
);
}
}