最近Flutterの開発で初心者の自分はこのエラーと出会って、解決策をこの記事にまとめました。
エラーメッセージ
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.
The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a
RenderObject, which has been set up to accept ParentData of incompatible type BoxParentData.
Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically,
Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a Padding widget.
The ownership chain for the RenderObject that received the incompatible parent data was:
RichText ← Text ← Expanded ← Padding ← Container ← _BodyBuilder ← MediaQuery ←
LayoutId-[<_ScaffoldSlot.body>] ← CustomMultiChildLayout ← AnimatedBuilder ← ⋯
原因
このエラーは、Flexible(), Expanded(), Positioned(), TableCell() ウィジェットなどの子ウィジェットに、該当する親ウィジェットがない場合に発生します。 例えば
Container(
Expanded(
child: Text("Hello FlutterCampus")
)
) //Error: Incorrect use of ParentDataWidget
解決策
Widget | Parent Widget |
---|---|
Expanded() | Row(), Column(), Flex() |
Flexible() | Row(), Column(), Flex() |
Positioned() | Stack() |
TableCell() | Table() |
Example Code
Row(
children:[
Expanded(
child: Text("Hello FlutterCampus")
)
]
)
OR:
Stack(
children:[
Positioned(
child: Text("Hello FlutterCampus")
)
]
)