Flutter Spacer引发的The ParentDataWidget Expanded(flex: 1) 惨案

问题描述

在flutter控制台中遇到如下报错:

bash 复制代码
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 StackParentData.

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 Stack widget.

The ownership chain for the RenderObject that received the incompatible parent data was:
  SizedBox.shrink ← Expanded ← Spacer ← Stack ← ConstrainedBox ← Padding ← Container ← Listener ← _GestureSemantics ← RawGestureDetector ← ⋯

问题分析

网上千篇一律的错误信息,都说是Expanded和Stack的关系问题。

但是排查代码中却没有任何地方使用到Expanded,而且由于报错没有指出在哪个页面,所以,问题一时间僵住了。

最后,通过一个一个注释代码块,确定问题大致代码块,最后按照SizedBox.shrink ← Expanded ← Spacer ← Stack ← ConstrainedBox ← Padding ← Container ← Listener ← _GestureSemantics ← RawGestureDetector ← ⋯顺序

一个一个在页面中排查,排查到Spacer,点击进去查看实现,Spacer的会当场build一个Expanded。

Spacer的源码如下:

dart 复制代码
class Spacer extends StatelessWidget {
  /// Creates a flexible space to insert into a [Flexible] widget.
  ///
  /// The [flex] parameter may not be null or less than one.
  const Spacer({super.key, this.flex = 1})
    : assert(flex > 0);

  /// The flex factor to use in determining how much space to take up.
  ///
  /// The amount of space the [Spacer] can occupy in the main axis is determined
  /// by dividing the free space proportionately, after placing the inflexible
  /// children, according to the flex factors of the flexible children.
  ///
  /// Defaults to one.
  final int flex;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: flex,
      child: const SizedBox.shrink(),
    );
  }
}

可以看到Spacer的build方法中,直接返回了一个Expanded,而Expanded的child是SizedBox.shrink()。这就是问题的根源。

解决方案

找到问题所在的页面,将Expanded和Spacer的关系注释掉,或者将Expanded的child改为Container,或者将Expanded的child改为Container()。

总结

不仅 Expanded 的使用限制在Flex/Row/Column中,Spacer 也有一样的限制。

相关推荐
YiWait4 分钟前
基于 Vue 3 的网络收音机,编译为桌面应用软件
前端·javascript·vue.js
虾壳云官方10 分钟前
OpenClaw 绑定企业微信完整指南
服务器·前端·网络·人工智能·企业微信·open claw·小龙虾
MichaelJohn10 分钟前
别卷框架了!前端人,用 JS + LangChain + DeepSeek 开启你的 AI 转型第一步
前端
古法编程第一人14 分钟前
使用Electric同步前后端数据
前端·vue.js
朱涛的自习室22 分钟前
30天11万行代码,我用 Trae 和 Gemini 造了个 AI 测试引擎
android·前端·人工智能
大连好光景26 分钟前
登录凭证 | Session+Cookie | Redis Token | JWT
前端·javascript
deepin_sir28 分钟前
11 - 模块与包
前端·数据库·python
小小小小宇39 分钟前
前端 Redux applyMiddleware 中间件链原理
前端
英俊潇洒美少年1 小时前
Vue 生产环境打包:SourceMap、压缩、混淆、Gzip、多环境配置 企业级最佳实践
前端·javascript·vue.js
2601_957786771 小时前
企业矩阵运营的“三段论“:管号、产内容、获线索——全链路系统的价值拆解
java·前端·矩阵·多平台管理