object - 如何在使用对象的下拉菜单中显示所选元素的名称?
问题描述
在这段代码中,我试图在下拉菜单中显示位置列表。在这里,我正在使用一个包含名称和 uid 的位置模型。有用。但是,我无法向用户显示所选选项。对我来说这里的对象是位置(this.name,this.uid)。
class DropButt extends StatelessWidget {
DropButt({Key key,this.locations,this.onchange});
// final String _selectedLocation='';
final List<Location> locations;
Function(Location) onchange;
@override
Widget build(BuildContext context) {
return DropdownButton<Location>(
//value:, here I donot know which value Should I put when I come to put //name it didnot accept it as dropdownbutton is of type location
items: locations.map((Location val) {
return new DropdownMenuItem<Location>(
value: val,
child: new Text(val.name),
);
}).toList(),
onChanged:(_){
onchange(_);
//here I will sink to the ream the value of th choosen location
},
);}
}
解决方案
您将设置当前选定位置的值。它需要传递给这个新的自定义无状态对象。
这是一个工作示例:
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Location _selectedLocation;
final _locations = [
new Location("home", "1"),
new Location("office", "2"),
new Location("work", "3"),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Sample"),),
body: DropButt(
_selectedLocation,
locations: _locations,
onchange: (location) {
setState(() {
_selectedLocation = location;
});
},
),
);
}
}
class DropButt extends StatelessWidget {
DropButt(this.selectedLocation, {Key key, this.locations, this.onchange});
final Location selectedLocation;
final List<Location> locations;
Function(Location) onchange;
@override
Widget build(BuildContext context) {
return DropdownButton<Location>(
value: selectedLocation, // <--- this is the current selected object
items: locations.map((Location val) {
return new DropdownMenuItem<Location>(
value: val,
child: new Text(val.name), // <--- this is what the user sees
);
}).toList(),
onChanged: onchange,
);
}
}
class Location {
final String name;
final String uid;
Location(this.name, this.uid);
}
推荐阅读
- r - 如何定义我的函数以保留 geom_point + geom_line
- swift - 在每个 TimeIntervalNotification 中不重复的随机元素
- devexpress - 如何在 WinAppDriver 中找到 DevExpress Grid Cell Active Editor 元素
- c++ - 蛇游戏:蛇的运动
- java - 如何使用 java css 处理 onkeypress 属性
- c++ - 错误:无法传递非平凡类型“std::string”的对象和更多错误
- android - 将自定义布局添加到生物识别提示
- java - 在另一个模块中获取资源的 URL
- php - 我们可以在谷歌云 ubuntu vm 实例中使用 xampp 作为在线服务器吗
- python - 如何在 python 中访问 numpy 结构化数组中的多个列值?