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

Flutter如何在Container中放置多个Widget解决child参数重复报错问题

报错原因
  • Container 是仅支持单个子组件的容器组件,不允许同时声明两次 child 参数,你代码里给同一个 Container 同时指定了 ListView.builder 和 FloatingActionButton 两个子组件,所以触发参数重复报错。
  • 你之前尝试改children不生效的原因是Container本身没有children属性,只有Column、Row、Stack这类多子布局组件才支持children参数传入多个组件。
解决方案

Scaffold 组件本身提供了专门的 floatingActionButton 配置项用来存放悬浮按钮,不需要把按钮放到 body 内部,调整代码结构即可:

  1. 把原本写在 Container 里的 FloatingActionButton 整块代码剪切,作为 Scaffold 的 floatingActionButton 参数的值
  2. 保留 Container 内的 ListView.builder 作为唯一的 child
  3. 同时修复原代码里 ! = null 的语法错误,去掉感叹号和等号之间的空格
修复后完整代码
@override
Widget build(BuildContext context) {
  double _width = MediaQuery.of(context).size.width;
  double _height = MediaQuery.of(context).size.height;
  return Scaffold(
    // 配置AppBar标题
    appBar: AppBar(
      title: Text('List of Lists'),
    ),
    body: Container(
      height: _height,
      width: _width,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            const Color(0xffe4a972).withOpacity(0.6),
            const Color(0xff9941d8).withOpacity(0.6), 
            const Color(0xff9941d8).withOpacity(0.6),
          ],
          begin: Alignment.topRight,
          end: Alignment.bottomLeft,
        ),
      ),
      child: ListView.builder(
        itemCount: todoList.length,
        itemBuilder: (context, index) {
          return Card(
            child: ListTile(
              title: Text(todoList[index]),
            ),
          );
        },
      ),
    ),
    // 悬浮按钮挪到Scaffold对应参数位置
    floatingActionButton: FloatingActionButton(
      onPressed: () async {
        // 跳转到新增待办页面,接收返回值
        final newListText = await Navigator.of(context).push(
          MaterialPageRoute(builder: (context) {
            return TodoAddPage();
          }),
        );
        if (newListText != null) {
          // 取消新增时返回值为null,仅非空时新增列表项
          setState(() {
            todoList.add(newListText);
          });
        }
      },
      child: Icon(Icons.add),
    ),
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:48:02