gpt4 book ai didi

dart - 如何在 flutter 中获取下拉按钮的选定索引

转载 作者:IT老高 更新时间:2023-10-28 12:32:03 26 4
gpt4 key购买 nike

如何在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 的类型。

video

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(),
),
),
),
);
}
}

关于dart - 如何在 flutter 中获取下拉按钮的选定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com