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

使用SimpleFoldingCell提示无默认构造函数的Dart报错如何解决

报错原因

你引用的示例代码使用的是folding_cell 1.x版本的API,而你当前项目安装的是2.0及以上版本的folding_cell包,该版本重构了SimpleFoldingCell的构造逻辑,移除了旧的默认无参构造,因此触发报错。

解决方案

有两种兼容方式可选:

方案1:降级依赖包版本(无需修改现有业务代码)

直接在项目的pubspec.yaml文件中修改folding_cell的版本约束为1.x系列:

dependencies:
  flutter:
    sdk: flutter
  folding_cell: ^1.0.0+1

修改后执行flutter pub get拉取对应版本包即可,原有代码可直接运行。

方案2:适配2.x版本的新API

如果需要使用新版本的特性,按以下步骤修改代码:

  1. 新增控制器列表存储每个折叠单元格的控制实例:
class _State extends State<Notific>{
  late List<TechnologyModel> _technologyList;
  // 新增控制器列表
  late List<FoldingCellController> _cellControllers;

  @override
  void initState() {
    super.initState();
    _technologyList = [
      TechnologyModel(title: "Application Development",),
      TechnologyModel(title: "Research & Development",),
      TechnologyModel(title: "Big Data & Analytics",),
      TechnologyModel(title: "Support Services",),
      TechnologyModel(title: "QA & Software Testing",),
    ];
    // 初始化对应数量的控制器
    _cellControllers = List.generate(_technologyList.length, (index) => FoldingCellController(initialOpen: false));
  }
  1. 修改SimpleFoldingCell的构造写法,传入必填的controller参数,其余参数和原有逻辑保持一致:
itemBuilder: (context, index) {
  return SimpleFoldingCell(
    // 传入对应位置的控制器,为必填参数
    controller: _cellControllers[index],
    frontWidget: _buildFrontWidget(index),
    innerTopWidget: _buildInnerWidget(index),
    innerBottomWidget: _buildInnerBottomWidget(),
    cellSize: Size(MediaQuery.of(context).size.width, 125),
    padding: EdgeInsets.all(15),
    animationDuration: Duration(milliseconds: 200),
    borderRadius: 10,
    onOpen: () => print('$index cell opened'),
    onClose: () => print('$index cell closed'),
  );
}
  1. 对应修改打开/关闭按钮的控制逻辑,直接调用对应位置控制器的toggleFold()方法即可,不需要再查找祖先状态:
// 打开按钮的点击逻辑修改为
FlatButton(
  onPressed: () {
    _cellControllers[index].toggleFold();
  },
  // 其余属性不变
)

// 关闭按钮的点击逻辑同理,你可以把index参数传到_buildInnerBottomWidget方法中,再调用对应控制器的toggleFold方法
额外提示

你代码中使用的FlatButton已经在新版本Flutter中被废弃,建议替换为TextButton组件避免后续警告。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:24:03