You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:25:14