Flutter BottomSheet中ParentDataWidget使用错误问题排查
问题场景
在showModalBottomSheet中使用如下Widget代码:
Flexible( child: ListView.separated( separatorBuilder: (context, index) => Container( height: 20.h, ), itemCount: 22, itemBuilder: (context, index) { return NagarTiming("test"); }), ),
开发环境运行时组件列表可正常显示,但打包APK安装到设备后,BottomSheet打开后内容空白,抛出以下错误:
the following assertion was thrown while applying parent data.: Incorrect use of ParentDataWidget.
The ParentDataWidget Flexible(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.
Usually, this means that the Flexible widget has the wrong ancestor RenderObjectWidget. Typically, Flexible widgets are placed directly inside Flex widgets. The offending Flexible is currently placed inside a SizedBox widget.
The ownership chain for the RenderObject that received the incompatible parent data was: _ScrollSemantics-[GlobalKey#f71a8] ← NotificationListener ← Scrollable ← PrimaryScrollController ← ListView ← Flexible ← SizedBox ← Column ← Padding ← Container ← ⋯ When the exception was thrown, this was the stack:
#0 RenderObjectElement._updateParentData. (package:flutter/src/widgets/framework.dart:5960:11)
核心原因
错误日志已明确指出问题:Flexible被放置在SizedBox内部,违反了组件布局规则。
Flexible是为Flex系列组件(Row/Column)设计的布局组件,作用是在Flex布局中分配剩余空间,必须直接作为Flex的子组件使用。当它被置于非Flex组件(如SizedBox)内部时,会尝试向子组件传递FlexParentData类型的布局数据,但目标RenderObject仅支持普通ParentData,数据类型不匹配触发断言错误,最终导致BottomSheet内容无法渲染。
开发环境与生产包表现差异,是因为生产编译时的断言检查更严格,开发环境存在部分容错机制,未直接触发错误。
修复方案
根据布局需求,可选择以下两种方式修复:
方案1:移除Flexible,适配ListView滚动
若无需Flex布局分配空间,直接移除Flexible,给ListView添加shrinkWrap: true让它自适应内容高度,同时给showModalBottomSheet设置isScrollControlled: true支持滚动:
ListView.separated( shrinkWrap: true, separatorBuilder: (context, index) => Container(height: 20.h), itemCount: 22, itemBuilder: (context, index) => NagarTiming("test"), ),
方案2:确保Flexible在Flex组件下
若需要ListView在Column等Flex布局中占满剩余空间,需保证Flexible直接作为Column的子组件,而非被SizedBox包裹:
Column( children: [ // 其他需要展示的组件 Flexible( child: ListView.separated( separatorBuilder: (context, index) => Container(height: 20.h), itemCount: 22, itemBuilder: (context, index) => NagarTiming("test"), ), ), ], ),
内容的提问来源于stack exchange,提问作者Jaimin Modi

