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

Flutter ListView动态创建Widget时报List非Widget子类型错误求助

问题原因
  • 你定义的getListOfWidgets方法返回List<Widget>类型,直接作为元素传入Column的children数组中,等于在Widget数组中嵌套了数组,不符合Column要求children每一项都是Widget的规则,因此抛出类型不匹配错误。
  • 你已经使用了DefaultTabController但未配套使用TabBarView,无法实现切换Tab展示对应分类内容的效果,不符合需求。
修改方案

直接替换原有代码为如下版本即可:

@override
Widget build(BuildContext context) {
  final cpProvider = Provider.of<CP>(context, listen: false);
  return DefaultTabController(
    length: cpProvider.adminStructures.length,
    child: Scaffold(
      backgroundColor: blue,
      appBar: AppBar(
        backgroundColor: blue,
        title: const Text('Select Category'),
        bottom: TabBar(
          labelStyle: const TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
          unselectedLabelStyle: const TextStyle(fontSize: 14.0),
          isScrollable: true,
          enableFeedback: true,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white,
          tabs: [
            for (final structure in cpProvider.adminStructures)
              Tab(text: structure.name),
          ],
        ),
        elevation: 0.0,
      ),
      // 替换原有Column为TabBarView,实现Tab和内容的联动
      body: TabBarView(
        children: [
          for (final structure in cpProvider.adminStructures)
            getCategoryWidget(structure)
        ],
      ),
    ),
  );
}

// 显式指定返回值为Widget,接收分类参数返回对应内容页
Widget getCategoryWidget(MyCategory structure) {
  final cpProvider = Provider.of<CP>(context, listen: false);
  List<Answer>? answers = cpProvider.catAndMembers[structure.uid];
  // 无对应Answer直接返回空白
  if (answers == null || answers.isEmpty) {
    return const SizedBox.shrink();
  }
  // 有Answer返回列表
  return ListView(
    shrinkWrap: true,
    children: answers.map((element) {
      return Text(element.fullName, style: const TextStyle(color: Colors.white));
    }).toList(),
  );
}
关键修改说明
  • 新增了TabBarView组件关联Tab控制器,切换Tab时会自动加载对应分类的内容
  • 将原getListOfWidgets方法调整为返回单个Widget类型,符合组件树的类型要求
  • 优化了Answer列表的构建逻辑,仅用一个ListView包裹所有列表项,避免嵌套多ListView导致的滚动冲突问题
  • 提前提取Provider实例,避免多次重复调用Provider.of提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:48:03