[英]How to get selected item's index number in DropdownButton in Flutter?
[英]how to get selected index of dropdownbutton in flutter
如何在 flutter 中获取下拉列表的 selectedIndex,
在下拉按钮中没有获取选定索引的属性,如果有如何获取选定索引,我的代码如下所示:
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(),
),
),),
您可能应该使用自定义模型对象(例如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>[User('Foo'), 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(),
),
),
),
);
}
}
与 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);
});
},
);
这为您提供了下拉列表的选定索引
userInfoToMap.indexOf(selectedUser);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.