Flutter中Draggable与DragTarget数据类型不匹配问题问询
解决Draggable与DragTarget数据类型不匹配问题
问题根源很明确:你的DragTarget特意指定了泛型<String>,但Draggable没有声明对应泛型类型,且传递的data是Map<FoodAttributes, bool>类型,两者类型不兼容,所以编译器认定DragTarget只能接收String?类型的数据。
修复步骤:
- 给
Draggable添加泛型声明<Map<FoodAttributes, bool>>,明确它传递的数据类型 - 将
DragTarget的泛型从<String>改为<Map<FoodAttributes, bool>>,和Draggable保持一致
修改后的代码示例:
child: DragTarget<Map<FoodAttributes, bool>>( builder: (context, candidateData, rejectedData) { return Container( width: 300, height: 300, alignment: Alignment.center, child: Image.asset('assets/images/Doggo3.png'), ); }, onWillAccept: (data) { return true; }, onAccept: (data) { // 现在data的类型是Map<FoodAttributes, bool>,和Draggable的data类型一致 }, ), class FoodWidget extends StatelessWidget { final Image image; final Map<FoodAttributes, bool> foodAttribute; const FoodWidget( {super.key, required this.image, required this.foodAttribute}); @override Widget build(BuildContext context) { return Draggable<Map<FoodAttributes, bool>>( data: foodAttribute, feedback: SizedBox(height: 90.0, width: 90.0, child: Center(child: image)), child: SizedBox( height: 90.0, width: 90.0, child: Center( child: image, ), ), ); } }
内容的提问来源于stack exchange,提问作者awwd
相关产品推荐
相关产品推荐

