如何在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
相关产品推荐
相关产品推荐

