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

Flutter&Dart:拖拽数据无法添加到userInput列表问题排查

问题分析与解决
  • 错误原因:你在onAccept的setState回调里每次都重新创建了userInput列表(List<Box> userInput = [];),这意味着每次拖拽完成时,你都是在一个全新的空列表里添加数据,之前添加的内容根本没被保留,所以打印出来的长度永远是1,列表自然不会增长。

  • 修复方案:把userInput定义为你的State类的成员变量,让它在组件的生命周期中持续存在,这样每次添加数据时都是在同一个列表里操作。

修改后的代码示例:

class _YourWidgetState extends State<YourWidget> {
  // 将userInput声明为State类的成员变量,仅初始化一次
  List<Box> userInput = [];

  Widget _generateOpaque(int index) {
    return DragTarget<Box>(
      builder: (BuildContext context, List<dynamic> accepted,
          List<dynamic> rejected) {
        return opaqueBoxes.elementAt(index).filled
            ? _filledBox(index)
            : _opaqueBox(index);
      },
      onWillAccept: (data) {
        return true;
      },
      onAccept: (data) {
        setState(() {
          // 直接在已有的列表中添加数据,不再重新初始化
          userInput.add(data);
          print(userInput.length); // 此时长度会随拖拽次数递增
        });
      },
    );
  }
}

这样修改后,userInput会一直保存之前添加的所有数据,每次拖拽完成调用add时,列表长度就会正确增长,打印结果也会符合预期。

内容的提问来源于stack exchange,提问作者grizzzzzy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:01:07