Flutter中如何基于Floor返回的Future列表生成DropMenuItem并解决类型不匹配报错
问题原因
你将FutureBuilder直接赋值给了DropdownButton的items参数,而items要求传入的是List<DropdownMenuItem>类型,FutureBuilder本身是Widget组件,类型不匹配所以触发报错。正确的写法是把FutureBuilder放在外层,异步请求拿到数据后再构建整个DropdownButton。
正确实现代码
首先在当前页面的State类中定义选中医生的状态变量:
Doctor? selectedDoctor;
替换你原来的DropdownButton部分代码:
FutureBuilder<List<Doctor>>( future: findAllDoctor(), builder: (context, snapshot) { // 加载中状态 if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } // 加载失败状态 if (snapshot.hasError) { return Text("加载失败:${snapshot.error}"); } // 拿到数据后构建下拉组件 final doctorList = snapshot.data ?? []; return DropdownButton<Doctor>( icon: const Icon(Icons.arrow_drop_down), hint: const Text('Select a doctor'), value: selectedDoctor, items: doctorList.map((doctor) => DropdownMenuItem<Doctor>( child: Text(doctor.name), value: doctor, )).toList(), onChanged: (val) { // 选中后更新页面状态 setState(() { selectedDoctor = val; }); print(val); }, ); }, )
注意事项
- 给
DropdownButton和DropdownMenuItem加上泛型<Doctor>,可避免后续出现隐式类型转换错误 - 选中值变化必须调用
setState更新selectedDoctor变量,下拉选中的状态才会正常回显 - 如果要集成到表单提交逻辑中,可直接读取
selectedDoctor的值,也可以配合Form组件的onSaved方法统一取数
内容的提问来源于stack exchange,提问作者Dhia Shalabi
相关产品推荐
相关产品推荐

