如何获得选择下拉的下拉列表,
在dropdown按钮中没有获取选定索引的属性,如果有如何获取所选索引,我的代码如下所示:
new DropdownButton( hint:new Text("Select a users"),value: selectedUser,
onChanged: (String newValue) {
setState(() {
selectedUser = newValue;
});
},
items: userInfoToMap.map((ListOfUsers value) {
return new DropdownMenuItem<String>(
value: value.name,
child:new Text(value.name,style: new TextStyle(color: Colors.black))
);
})
.toList(),
),
),),
Run Code Online (Sandbox Code Playgroud)
Col*_*son 25
您应该使用自定义模型对象(例如User)作为类型DropdownButton.
import'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class User {
const User(this.name);
final String name;
}
class MyApp extends StatefulWidget {
State createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
User selectedUser;
List<User> users = <User>[const User('Foo'), const User('Bar')];
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new Center(
child: new DropdownButton<User>(
hint: new Text("Select a user"),
value: selectedUser,
onChanged: (User newValue) {
setState(() {
selectedUser = newValue;
});
},
items: users.map((User user) {
return new DropdownMenuItem<User>(
value: user,
child: new Text(
user.name,
style: new TextStyle(color: Colors.black),
),
);
}).toList(),
),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
与Collin Jackson的答案类似,您可以简单地使用字符串列表并检查indexOf来设置值,这在某些情况下可能比使用User类更好。如果要设置初始值,请在定义时将_user设置为整数值。
int _user;
...
var users = <String>[
'Bob',
'Allie',
'Jason',
];
return new DropdownButton<String>(
hint: new Text('Pickup on every'),
value: _user == null ? null : users[_user],
items: users.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
_user = users.indexOf(value);
});
},
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14940 次 |
| 最近记录: |