gpt4 book ai didi

object - 如何在使用对象的下拉菜单中显示所选元素的名称?

转载 作者:IT王子 更新时间:2023-10-29 07:12:58 26 4
gpt4 key购买 nike

在此代码中,我试图在下拉菜单中显示位置列表。在这里,我正在使用一个包含名称和 uid 的位置模型。有用。但是,我无法向用户显示所选选项。对我来说这里的对象是 Location(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);
}

关于object - 如何在使用对象的下拉菜单中显示所选元素的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53722567/

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