在这段代码中,我试图在下拉菜单中显示位置列表。在这里,我正在使用由名称和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
},
);}
}
答案 0 :(得分:2)
您将设置当前所选位置的值。需要将其传递给这个新的自定义无状态对象。
这是一个工作示例:
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);
}