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

如何在Flutter的RichText中添加‘查看更多’按钮?

解决方案

步骤1:调整文本加粗解析逻辑

保留你通过**标记实现文本加粗的核心逻辑,通过正则替换将**转为单个*后拆分文本,识别奇数位片段为加粗内容。

步骤2:集成展开收起功能

利用readmore包的ReadMoreText组件,将解析后的富文本片段传入,同时配置印尼语的展开/收起按钮文本及样式。

完整代码

import 'package:flutter/material.dart';
import 'package:readmore/readmore.dart';

class BoldAsteris extends StatefulWidget {
  final String text;
  final int trimLines; // 可自定义收起时显示的行数

  const BoldAsteris({
    super.key,
    required this.text,
    this.trimLines = 2, // 默认收起显示2行
  });

  @override
  State<BoldAsteris> createState() => _BoldAsterisState();
}

class _BoldAsterisState extends State<BoldAsteris> {
  @override
  Widget build(BuildContext context) {
    // 处理**标记,转为单个*方便拆分识别
    String processedText = widget.text.replaceAll(RegExp(r'\*\*'), "*");
    List<String> textSegments = processedText.split('*');
    
    // 生成带加粗样式的TextSpan列表
    List<TextSpan> textSpans = List.generate(textSegments.length, (index) {
      return TextSpan(
        text: textSegments[index],
        style: index.isOdd
            ? const TextStyle(fontWeight: FontWeight.bold)
            : const TextStyle(color: Colors.black, fontSize: 17),
      );
    });

    return ReadMoreText(
      "", // 使用customTextSpan时此处传空字符串
      customTextSpan: TextSpan(children: textSpans),
      trimLines: widget.trimLines,
      trimCollapsedText: ' baca selengkapnya',
      trimExpandedText: ' tutup',
      colorClickableText: Colors.blue,
      style: const TextStyle(color: Colors.black, fontSize: 17),
      moreStyle: const TextStyle(
          fontSize: 17, fontWeight: FontWeight.bold, color: Colors.blue),
      lessStyle: const TextStyle(
          fontSize: 17, fontWeight: FontWeight.bold, color: Colors.blue),
    );
  }
}

使用示例

// 在页面中调用组件
BoldAsteris(
  text: "Ini adalah **contoh teks** dengan fitur baca selengkapnya. **Bagian tebal** akan terlihat jelas ketika ditampilkan.",
  trimLines: 2,
)

关键说明

  • 将组件改为StatefulWidget适配ReadMoreText的状态管理逻辑
  • trimLines参数可根据需求调整收起时显示的行数
  • 展开按钮文本为印尼语baca selengkapnya,收起按钮为tutup
  • 保留你原有的加粗解析逻辑,确保**包裹的内容正确显示为粗体样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:02:02