Flutter使用GridView时出现"Incorrect use of ParentDataWidget"报错如何解决
问题根因
报错的核心原因是Expanded组件仅可作为Row、Column、Flex三类组件的直接子节点使用,本次报错触发是因为Expanded被放在了非Flex组件下:大概率是你自定义的ImageCircle组件内部使用了Expanded,而GridView的子节点外层默认被RepaintBoundary包裹,父数据类型不匹配,触发了断言。
解决步骤
- 先排查
ImageCircle的实现代码,删除直接挂载在非Flex组件下的Expanded/Flexible组件;如果确实需要弹性布局,要保证Expanded的直接父组件为Row/Column/Flex。 - 针对GridView自适应高度的需求,你已经配置了
shrinkWrap: true让GridView高度适配自身内容,由于GridView放在Column组件内,为了避免内容过长导致Column溢出,需要给GridView外层套一层Expanded,让它占用Column除顶部AppBar、底部固定Row之外的剩余空间,内容超出时可滚动。
修正后核心代码示例
@override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SafeArea( child: Column(children: <Widget>[ AppBar( backgroundColor: Colors.grey, actions: [ IconButton(onPressed: () {}, icon: Icon(Icons.search)), ], ), // 新增Expanded包裹GridView Expanded( child: GridView.count( primary: false, crossAxisCount: 4, shrinkWrap: true, children: List.of(foodBrain.getFoodList().map((food) => ImageCircle( fileName: food.fileName, displayName: food.displayName, text: food.text, ))), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only(top: 5.0, right: 16.0), child: Text( 'Click when done', style: kButtonTextStyle, ), ), IconButton( onPressed: () { Navigator.pushNamed(context, PassoverList.id); }, icon: Icon(FontAwesomeIcons.list), iconSize: 30.0, color: Colors.blueAccent, ), ], ), ]), ), ); }
内容的提问来源于stack exchange,提问作者nordan
相关产品推荐
相关产品推荐

