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

在CustomScrollView中使用TextField报错,寻求无固定尺寸解决办法

问题解决:CustomScrollView中TextField报错且无需固定宽高

问题根源

设置了expands: true的TextField需要父组件提供明确的垂直空间约束,但SliverToBoxAdapter在CustomScrollView里无法传递这种约束,导致布局冲突报错。

解决方案

下面提供两种无需固定宽高的解决办法:

方案一:移除expands: true,让TextField随内容自适应高度

如果不需要TextField强制占满空间,只需要它随输入内容自动调整高度,直接去掉expands: true即可,保留minLines: null和maxLines: null就能支持无限换行:

class MyCustomTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextField(
      minLines: null,
      maxLines: null, // 高度随输入内容动态变化
      scrollPadding: EdgeInsets.all(0),
      decoration: InputDecoration(),
      style: TextStyle(fontSize: 16.0),
    );
  }
}

方案二:用SliverFillRemaining替代SliverToBoxAdapter,让TextField填充剩余空间

如果需要TextField占满CustomScrollView的剩余可用空间,把SliverToBoxAdapter换成SliverFillRemaining,它会自动给子组件传递填充剩余空间的约束,适配expands: true的设置:

class MyAppc extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: CustomScrollView(
            slivers: [
              SliverFillRemaining(
                child: MyCustomTextField(),
              )
            ],
          ),
        ),
      ),
    );
  }
}

如果还有其他Sliver组件(比如SliverAppBar),SliverFillRemaining也会自动占据这些组件之后的剩余空间,无需设置固定高度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:33:24