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

在Card中嵌套ListTile出现RenderBox was not laid布局报错如何解决

报错原因

这个hasSize布局报错本质是布局流程被异常打断导致的,具体触发点有两个:

  • onChanged回调中存在非法类型转换:offerAmount是输入的字符串内容,直接用as int强转会抛出类型异常,中断布局渲染。
  • 尾随文本直接调用控制器的toString()方法,输出的是控制器实例信息而非输入内容,控制器未正常初始化也会进一步触发渲染异常。
修复步骤
  1. 修正类型转换逻辑,使用安全的数字解析方法
    替换原有onChanged代码:
// 原代码
onChanged: (offerAmount) => _offerAmount = offerAmount as int,
// 修改后代码
onChanged: (offerAmount) => _offerAmount = int.tryParse(offerAmount) ?? 0,
  1. 修正尾随文本的取值逻辑,取控制器的text属性获取输入内容
    替换ListTile部分代码:
Card(
  margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
  child: ListTile(
    leading: const Text('Fee'),
    trailing: Text(_offerController.text),
  )
)
  1. 补充控制器初始化逻辑,适配空安全配置
    在State类中增加控制器的初始化与销毁逻辑:
late TextEditingController _offerController;
late int _offerAmount;

@override
void initState() {
  super.initState();
  _offerController = TextEditingController();
  _offerAmount = 0;
}

@override
void dispose() {
  _offerController.dispose();
  super.dispose();
}
  1. 可选优化:补充数字输入限制,避免非数字内容输入
    修改inputFormatters配置,只允许输入数字:
inputFormatters: <TextInputFormatter>[
  FilteringTextInputFormatter.digitsOnly,
  FilteringTextInputFormatter.singleLineFormatter
],
修复后完整代码片段
ListView(children: [
  Padding(
    padding: const EdgeInsets.symmetric(
      horizontal: 16.0,
      vertical: 10.0,
    ),
    child: TextFormField(
      controller: _offerController,
      textInputAction: TextInputAction.next,
      decoration: const InputDecoration(
        hintText: '5-9999',
        prefixIcon: Icon(Icons.attach_money_rounded),
        labelText: 'Your Offer',
      ),
      keyboardType: TextInputType.number,
      inputFormatters: <TextInputFormatter>[
        FilteringTextInputFormatter.digitsOnly,
        FilteringTextInputFormatter.singleLineFormatter
      ],
      onChanged: (offerAmount) => _offerAmount = int.tryParse(offerAmount) ?? 0,
    ),
  ),
  Card(
    margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
    child: ListTile(
      leading: const Text('Fee'),
      trailing: Text(_offerController.text),
    )
  )
]),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:36:03