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

如何在Glance AppWidget中使用复数字符串资源?

在Widget中使用复数字符串资源的解决方法

1. 简单场景:直接条件判断

如果只需要区分单数和复数两种情况,用三元运算符直接处理最省心,不需要额外扩展:

Text(
  itemCount == 1 
      ? '1 条消息' 
      : '$itemCount 条消息',
)

2. 复杂规则:自定义工具函数

要是需要处理零、单数、复数等多种分支逻辑,写个独立工具函数封装规则:

String getPluralText(int count) {
  if (count == 0) return '暂无内容';
  if (count == 1) return '1 条内容';
  return '$count 条内容';
}

// 在Widget里直接调用
Text(getPluralText(list.length))

3. 自定义上下文扩展方法

既然系统没有现成的扩展,自己给BuildContext加一个,后续使用更便捷:

// 先定义扩展类
extension PluralHelper on BuildContext {
  // 基础版:仅区分单复数
  String plural(String singleForm, String pluralForm, int count) {
    return count == 1 ? singleForm : pluralForm.replaceAll('{count}', count.toString());
  }

  // 进阶版:支持零值场景
  String pluralWithZero(String zeroForm, String singleForm, String pluralForm, int count) {
    if (count == 0) return zeroForm;
    if (count == 1) return singleForm;
    return pluralForm.replaceAll('{count}', count.toString());
  }
}

// 使用示例
Text(context.plural('1 个文件', '{count} 个文件', fileCount))
// 进阶版调用
Text(context.pluralWithZero('没有文件', '1 个文件', '{count} 个文件', fileCount))

补充:多语言场景提示

如果是多语言项目,推荐用intl包的复数API来适配不同语言的复数规则;但如果不想引入第三方依赖,上面的自定义方案完全能覆盖日常需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:57:05