Reputation: 107
I have build the code of DropdownMenuItem, now when i click an item from dropdownmenuitem it should move to another screen.Below is the code
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'
),
),)]
Upvotes: 1
Views: 5110
Reputation: 48
After applying fayeed's solution, I noticed that this only makes the text inside the dropdown clickable. To fix this, you can simply use DropdownButton.onChanged
.
Full widget:
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;
}
},
);
}
}
Upvotes: -1
Reputation: 2485
You can wrap your Text
widget with GestureDetector
to which has an onTap
function which you can use to execute your desired code. For more details look at this: https://api.flutter.dev/flutter/widgets/GestureDetector-class.html
This should work:
DropdownMenuItem(
value: 'Earth',
child: GestureDetector(
onTap: () {
// navigate code...
},
child: Text('Earth')
),
),
Upvotes: 2