I want to change my DropdownButton
selected index on page load, how can I do that?
My DropdownButton
is a list of PlateType
objects and I need to change the selected index to some index that means old user selection.
Following is my code:
DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: false,
child: new DropdownButton<PlateType>(
hint: new Text(
"حرف",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
value: selectedPlate,
isExpanded: false,
iconSize: 30,
style: new TextStyle(
color: Colors.white,fontFamily: 'iransans',
),
onChanged: (PlateType pt) {
setState(() {
selectedPlate = pt;
});
},
items: plates.map((PlateType p) {
return new DropdownMenuItem<PlateType>(
value: p,
child: new Text(
p.name,
textAlign: TextAlign.center,
style: new TextStyle(color: Colors.black),
),
);
}).toList(),
)
)
)
If you want select default value on page load for DropDown, you can declare list globally and then set default value before widget called such as below:
import 'package:flutter/material.dart';
import 'package:flutter_app/models/User.dart';
List<User> userList = new List<User>();
User selectedUser;
class MyDropDownForm extends StatefulWidget {
createState() {
userList.add(new User(name: 'ABC', age: '25'));
userList.add(new User(name: 'SDF', age: '24'));
userList.add(new User(name: 'FGDG', age: '23'));
userList.add(new User(name: 'PQR', age: '28'));
userList.add(new User(name: 'XFGDF', age: '29'));
userList.add(new User(name: 'WWW', age: '26'));
userList.add(new User(name: 'HHH', age: '30'));
userList.add(new User(name: 'RFD', age: '35'));
selectedUser = userList[0];
return StateKeeper();
}
}
class StateKeeper extends State<MyDropDownForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Center(
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: false,
child: new DropdownButton<User>(
hint: new Text(
"حرف",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
value: selectedUser,
isExpanded: false,
iconSize: 30,
style: new TextStyle(
color: Colors.white,fontFamily: 'iransans',
),
onChanged: (User pt) {
setState(() {
selectedUser = pt;
print("Selected user " + selectedUser.name);
});
},
items: userList.map((User p) {
return new DropdownMenuItem<User>(
value: p,
child: new Text(
p.name,
textAlign: TextAlign.center,
style: new TextStyle(color: Colors.black),
),
);
}).toList(),
)
)
)
],
),
),
),
);
}
}
User model class:
class User {
String name;
String age;
User({
this.name,
this.age,
});
factory User.fromJson(Map<String, dynamic> json) => new User(
name: json["name"],
age: json["age"],
);
Map<String, dynamic> toJson() => {
"name": name,
"age": age,
};
}