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

Flutter中如何在三元运算符中使用contentPadding当前属性值?

解决方案

你可以通过以下两种方式实现需求:

场景1:使用InputDecoration默认内边距

当标记为Off时,直接将contentPadding设为null即可,Flutter会自动使用InputDecoration内置的默认内边距,等同于“不做更改”:

TextField(
  decoration: InputDecoration(
    contentPadding: someBoolFlagIsOn ? EdgeInsets.zero.copyWith(left: 10) : null,
    // 其他装饰属性...
  ),
)

场景2:使用自定义默认内边距

如果你预先定义了需要保留的自定义内边距值,直接在else分支返回该值即可:

// 预先定义你想要保留的默认内边距
final EdgeInsets defaultContentPadding = const EdgeInsets.symmetric(horizontal: 16, vertical: 12);

TextField(
  decoration: InputDecoration(
    contentPadding: someBoolFlagIsOn ? EdgeInsets.zero.copyWith(left: 10) : defaultContentPadding,
    // 其他装饰属性...
  ),
)

核心逻辑是利用三元运算符的分支,在标记为On时返回修改后的内边距,标记为Off时返回需要保留的内边距值(默认值或自定义值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:09:56