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

如何在Flutter中将字符串转换为Title Case格式?

Flutter/Dart 字符串转标题格式(Title Case)实现方案

以下是一个完全基于Dart核心API的实现,无需依赖任何第三方库或Flutter中不存在的函数,可直接在Flutter项目中使用:

实现代码(扩展方法)

extension StringTitleCase on String {
  String toTitleCase() {
    if (isEmpty) return this;

    // 处理多空格、首尾空格,分割为单词列表
    final words = trim().split(RegExp(r'\s+'));

    return words.map((word) {
      if (word.length == 1) {
        return word.toUpperCase();
      }
      // 首字母大写,其余部分保持小写
      return '${word[0].toUpperCase()}${word.substring(1).toLowerCase()}';
    }).join(' ');
  }
}

使用示例

void main() {
  const input1 = "hello flutter world";
  print(input1.toTitleCase()); // 输出: Hello Flutter World

  const input2 = "ALL UPPERCASE TEXT";
  print(input2.toTitleCase()); // 输出: All Uppercase Text

  const input3 = "  text with   multiple spaces  ";
  print(input3.toTitleCase()); // 输出: Text With Multiple Spaces
}

说明

  • 自动处理首尾空格、连续多空格的情况
  • 兼容全小写、全大写、混合格式等各种输入
  • 完全依赖Dart原生API,不存在Flutter中找不到函数的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:24:35