[英]How to get selected item's index number in DropdownButton in Flutter?
[英]How to change DropdownButton's selected index in Flutter
我想在頁面加載時更改我的DropdownButton
所選索引,該怎么辦?
我的DropdownButton
是PlateType
對象的列表,我需要將選定的索引更改為某些索引,這意味着要選擇舊用戶。 以下是我的代碼:
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(),
)
)
)
如果要在頁面加載時為DropDown選擇默認值,則可以全局聲明list,然后在名為的小部件之前設置默認值,如下所示:
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(),
)
)
)
],
),
),
),
);
}
}
用戶模型類:
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,
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.