Flutter如何在Container中放置多个Widget解决child参数重复报错问题
报错原因
Container是仅支持单个子组件的容器组件,不允许同时声明两次child参数,你代码里给同一个Container同时指定了ListView.builder和FloatingActionButton两个子组件,所以触发参数重复报错。- 你之前尝试改
children不生效的原因是Container本身没有children属性,只有Column、Row、Stack这类多子布局组件才支持children参数传入多个组件。
解决方案
Scaffold 组件本身提供了专门的 floatingActionButton 配置项用来存放悬浮按钮,不需要把按钮放到 body 内部,调整代码结构即可:
- 把原本写在 Container 里的 FloatingActionButton 整块代码剪切,作为 Scaffold 的
floatingActionButton参数的值 - 保留 Container 内的 ListView.builder 作为唯一的 child
- 同时修复原代码里
! = 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
相关产品推荐
相关产品推荐

