You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Expanded放在Align内触发ParentData错误如何解决?

问题根源

Expanded 组件只能作为 Row、Column、Flex 这三种 Flex 布局组件的直接子组件使用,它依赖父级 Flex 组件提供的布局规则分配剩余空间。你的代码中将 Expanded 直接放在了设置了 alignment 属性的 Container 内部,Container 不属于 Flex 布局组件,无法识别 Expanded 携带的布局参数,因此抛出类型不兼容的异常。同时你代码中还有另一处同类错误:包裹 SelectableText 的 Flexible 父组件是固定宽度的 Container,也不符合 Flexible 的使用规则。

修复步骤
  1. 直接删除包裹 Column 外层的 Expanded 组件,你的 Container 已经设置了 width: double.infinity 占满横向宽度,不需要 Expanded 来占空间。
  2. 删除包裹 SelectableText.rich 外层的 Flexible 组件,外层 100 宽度的 Container 已经限制了文本最大宽度,超出会自动换行,不需要 Flexible 参与布局。
修正后的核心代码片段
@override
Widget build(BuildContext context) {
  double screenWidth = MediaQuery.of(context).size.width;

  return MouseRegion(
      onEnter: (event) {
        _isHovered = true;
        setState(() {});
      },
      onExit: (event) {
        _isHovered = false;
        setState(() {});
      },
      child: Container(
        width: double.infinity,
        constraints: BoxConstraints(
          minHeight: 40,
        ),
        padding: EdgeInsets.only(
          top: 7,
          bottom: 7,
        ),
        alignment: Alignment.centerLeft,
        // 删掉了原来的Expanded
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            Container(
              margin: EdgeInsets.only(top: 2, left: 0),
              padding: EdgeInsets.only(left: 2, right: 2),
              decoration: BoxDecoration(
                border: Border.all(
                  color: Color(0xff80838a).withOpacity(0.6),
                ),
                borderRadius: BorderRadius.circular(2),
              ),
              child: Text(
                'Translation',
                style: TextStyle(
                  color: Color(0xff80838a),
                  fontSize: 15,
                ),
              ),
            ),
            Container(
                width: 100,
                // 删掉了原来的Flexible
                child: SelectableText.rich(
                  TextSpan(
                    children: [
                      TextSpan(text: widget.wordTranslation.text),
                    ],
                  ),
                  style: Theme.of(context).textTheme.bodyText2.copyWith(height: 1.4, fontSize: 16),
                )),
            if ((widget.wordTranslation.audioUrl ?? '').isNotEmpty && _isHovered)
              Container(
                margin: EdgeInsets.only(left: 10),
                child: SoundPlayButton(
                  audioUrl: widget.wordTranslation.audioUrl,
                ),
              ),
          ],
        ),
      ));
}

内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:36:05