When you implement the Dropdown Button with DropdownMenuItem, you may experience not switching of Items to Selected Value. In this example, we are going to show you the full working example of Dropdown Button in Flutter.
First, you need to implement your widget build to StatefulWidget, because, you have to track the select value. You will not able to update app state or UI in StatelessWidget App.
List<String> listitems = ["Tokyo", "London", "New York", "Sanghai", "Moscow", "Hong Kong"];
String selectval = "Tokyo";
DropdownButton(
value: selectval, //implement initial value or selected value
onChanged: (value){
setState(() { //set state will update UI and State of your App
selectval = value.toString(); //change selectval to new value
});
},
items: listitems.map((itemone){
return DropdownMenuItem(
value: itemone,
child: Text(itemone)
);
}).toList(),
)
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp( home: MyApp(),)
);
}
class MyApp extends StatefulWidget{
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<String> listitems = ["Tokyo", "London", "New York", "Sanghai", "Moscow", "Hong Kong"];
String selectval = "Tokyo";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("Dropdown Button in Flutter"),
backgroundColor: Colors.deepPurpleAccent
),
body: Container(
margin: EdgeInsets.only(top:50),
alignment: Alignment.topCenter,
child: DropdownButton(
value: selectval,
onChanged: (value){
setState(() {
selectval = value.toString();
});
},
items: listitems.map((itemone){
return DropdownMenuItem(
value: itemone,
child: Text(itemone)
);
}).toList(),
),
)
);
}
}
In this way, you can switch newly selected value from current value on DropdownButton widget in Flutter.
Please Wait...
No any Comments on this Article