Flutter动态生成下拉框:如何获取每个下拉框的独立值
解决动态生成下拉框并获取独立值的问题
这个需求其实很常见,核心就是用列表来对应存储每个动态生成的下拉框的值——毕竟下拉框数量不固定,单个变量肯定hold不住。下面是具体的实现步骤和修改后的代码:
1. 先加个列表存每个下拉框的值
在你的State类里,新增一个列表变量,专门用来保存每个儿子的年龄值:
bool sonVisible = false; bool sonChecked = false; String sonCount; int sonListCount = 0; bool sonDropDown = false; // 新增:每个元素对应一个下拉框的选中值 List<String> sonAges = [];
2. 选完儿子数量就初始化列表
当用户选好儿子数量后,我们得把列表的长度调整成和下拉框数量一致,这样每个下拉框都能对应到列表里的位置:
CustomCountDropDown( ageValue: sonCount, onChanged: (val) { setState(() { sonCount = val; sonListCount = int.parse(sonCount); // 初始化列表,长度等于儿子数量,默认值设为空就行(也可以设成默认年龄) sonAges = List.filled(sonListCount, ''); sonDropDown = true; }); }, decoration: spinnerDecoration('No of Son'), )
3. 给每个动态下拉框绑定对应的值
在GridView.builder的itemBuilder里,把每个下拉框和列表的对应索引绑定,选值的时候直接更新列表里的对应位置:
return CustomAgeDropDown( decoration: spinnerDecoration('Age Son - ${index + 1}'), // 把当前索引的列表值传给下拉框 ageValue: sonAges[index], onChanged: (value) { setState(() { // 更新对应索引的年龄值 sonAges[index] = value; // 想调试的话可以打印看看,比如第一个儿子的年龄就是sonAges[0] print('Son ${index+1} age: ${sonAges[index]}'); }); }, );
4. 给CustomAgeDropDown明确类型(可选但更规范)
为了避免编辑器报类型警告,建议把CustomAgeDropDown的onChanged参数类型明确一下:
class CustomAgeDropDown extends StatefulWidget { final String ageValue; final InputDecoration decoration; // 明确是接收String类型的回调 final Function(String) onChanged; CustomAgeDropDown({ this.ageValue, this.decoration, this.onChanged }); @override _CustomAgeDropDownState createState() => _CustomAgeDropDownState(); }
这样改完之后,你就可以通过sonAges列表拿到每个下拉框的独立值了——比如要拿第三个儿子的年龄,直接取sonAges[2]就行(因为列表是从0开始索引的)。
内容的提问来源于stack exchange,提问作者Jorden
相关产品推荐
相关产品推荐

