首页 > 解决方案 > 如何在使用对象的下拉菜单中显示所选元素的名称?

问题描述

在这段代码中,我试图在下拉菜单中显示位置列表。在这里,我正在使用一个包含名称和 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
                    },
                  );}

}

标签: objectdrop-down-menuflutter

解决方案


您将设置当前选定位置的值。它需要传递给这个新的自定义无状态对象。

这是一个工作示例:

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

推荐阅读