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

如何在Flutter的.arb文件中转义单引号?

Flutter ARB文件单引号转义问题解决方法

问题场景

在Flutter国际化的intl_en.arb文件中,编写如下内容时:

"title_chef_selection": "Chef's Selection",
"@title_chef_selection": {},

会触发错误:

Error: Unbalanced escape quotes. To escape a single quote ', prefix it with another single quote.(mismatched_brackets)

按提示修改为Chef''s Selection后,在Text(S.of(context).title_chef_selection)中会显示两个单引号,不符合需求。

改用反斜杠转义Chef\'s Selection,文本显示正常,但会报JSON格式错误:

Invalid escape character in string.json(261)

正确解决方法

方法1:直接保留单引号(推荐)

ARB本质是JSON格式,双引号包裹的字符串内,单引号不属于JSON规定的需要转义的字符,直接编写即可。如果工具报错,大概率是intl相关插件或linter的误判,可尝试:

  • 升级intl及intl_utils包到最新版本
  • 检查IDE的Flutter国际化插件配置,关闭不必要的严格语法检查

正确写法:

"title_chef_selection": "Chef's Selection",
"@title_chef_selection": {},

方法2:用单引号包裹字符串(兼容写法)

部分JSON解析器允许用单引号包裹字符串值,此时内部单引号可通过反斜杠转义,Flutter intl工具链通常支持这种写法:

"title_chef_selection": 'Chef\'s Selection',
"@title_chef_selection": {},

注意:此写法不符合严格JSON规范,但在Flutter国际化场景下可正常工作。

方法3:占位符间接处理(特殊场景)

如果上述方法都不适用,可通过占位符拆分字符串:

"title_chef_selection": "Chef{apostrophe}s Selection",
"@title_chef_selection": {
  "placeholders": {
    "apostrophe": {}
  }
}

代码中调用时传入单引号:

Text(S.of(context).title_chef_selection(apostrophe: "'"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:38:09