首页 > 解决方案 > 单击下拉按钮时传递对象的属性

问题描述

我有一堂课:

class Venue{
Venue({this.id,this.name});
String id;
String name;
}

我的 dropdownButton 包含venue.name场地列表中的列表。

单击按钮时,我想将同一对象(我单击的)的 id 传递给树上它下方的另一个小部件。这是我的下拉小部件:

class SelectVenue extends StatefulWidget {
  final String id;
  SelectVenue({this.id});
  static const String ALL_VENUES = 'All Venues';
  @override
  _SelectVenueState createState() => _SelectVenueState();
}

class _SelectVenueState extends State<SelectVenue> {
  static const String all_venues = "All Venues";
  String dropdownValue = all_venues;
  Future<List<Venue>> venues;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Venue>>(
        future: venues,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final venues = snapshot.data;
            checkNoVenues(venues);
            return DropdownButton<String>(
              value: dropdownValue,
              icon: Icon(
                Icons.keyboard_arrow_down,
                color: Colors.black,
                size: 28,
              ),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.black),
              onChanged: (String newValue) {
                setState(() {
                  dropdownValue = newValue;
                });
              },
              items: venues.map((venue) {
                return DropdownMenuItem<String>(
                  value: venue.name,
                  child: Text(
                    venue.name,
                    style: TextStyle(fontSize: 28),
                  ),
                );
              }).toList(),
            );
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        });
  }

标签: flutter

解决方案


String id = '';

...
//inside dropdown onChanged
onChanged:(value){
 ///get id of the selected drop down venue
 id = venues.where((venue)=>venue.name==dropdownValue).id;
}

在同一个小部件类中进一步向下访问 id 参数


推荐阅读