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

如何在Flutter(Dart)中拆分多语句文本并分Text widget展示?

Flutter 按句子拆分文本并分别显示在Text组件中

要实现将文本拆分为第一句和剩余内容并分别放入不同Text组件,关键是准确识别第一个句子的结束位置,以下是具体实现方案:

实现思路

通过正则表达式匹配句子结束的标准标点(!、.、?),且标点后需紧跟空格或文本结尾,以此定位第一个句子的边界,再拆分字符串。

代码示例

void main() {
  var str = 'Taste the crunchy and spicy goodness of our potato chips! Our chips are sure to tantalize your taste buds, leaving you wanting more! And with their irresistible flavor, you won\'t be able to resist the temptation to indulge. So why not grab a bag today and experience the deliciousness of our potato chips? You won\'t regret';
  
  // 匹配句子结束标点,确保标点后是空格或文本结尾
  final sentenceEndRegex = RegExp(r'([.!?])(?=\s|$)');
  final firstMatch = sentenceEndRegex.firstMatch(str);

  String firstSentence = '';
  String remainingText = '';

  if (firstMatch != null) {
    // 截取第一句(包含结束标点)
    firstSentence = str.substring(0, firstMatch.end).trim();
    // 截取剩余内容,去除开头多余空格
    remainingText = str.substring(firstMatch.end).trim();
  } else {
    // 无句子分隔符时,全部内容作为第一句
    firstSentence = str.trim();
    remainingText = '';
  }

  // Flutter中组件使用示例
  // return Column(
  //   crossAxisAlignment: CrossAxisAlignment.start,
  //   children: [
  //     Text(
  //       firstSentence,
  //       style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
  //     ),
  //     if (remainingText.isNotEmpty)
  //       Text(
  //         remainingText,
  //         style: TextStyle(fontSize: 16),
  //       ),
  //   ],
  // );

  // 打印测试
  print('第一句:$firstSentence');
  print('剩余内容:$remainingText');
}

说明

  • 正则表达式r'([.!?])(?=\s|$)'确保匹配的是完整句子的结束标点,避免误拆分引号内或缩写中的标点。
  • 处理了无句子分隔符的边界情况,避免空指针或异常。
  • 若需处理更复杂的文本结构(如包含括号、引号内的标点),可调整正则表达式适配场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:00:41