Flutter文本展示与URL点击插件read_more_text_url的使用

Flutter文本展示与URL点击插件read_more_text_url的使用

read_more_text_url 是一个 Flutter 包,它提供了一个带有高级功能的“更多/更少”文本扩展小部件,包括 URL 和电子邮件检测、自定义链接样式、动态模式匹配以及链接点击操作。

功能

  • 文本扩展:无缝切换展开和折叠的文本。
  • URL 和电子邮件检测:自动检测并高亮文本中的 URL 和电子邮件地址。
  • 自定义链接样式:为检测到的链接应用自定义样式。
  • 动态模式匹配:提供自定义正则表达式以匹配特定文本并为其设置样式。
  • 点击操作:处理链接点击事件并检测点击的是哪个链接。

安装

在你的 Flutter 项目的 pubspec.yaml 文件中添加以下依赖:

read_more_text_url: ^0.0.2

运行 flutter pub get 来安装包。然后,在 Dart 代码中导入它:

import 'package:read_more_text_url/read_more_text.dart';

入门

以下是一个如何在 Flutter 应用中使用 ReadMoreText 小部件的基本示例:

ReadMoreText(
  "Read more and read less is used to improve the page text visibility. It allows users to read the page's full content by pressing the read more button and hiding the content by pressing the read less button.",
  trimCollapsedText: 'Show more',
  trimExpandedText: 'Show less',
  trimMode: TrimMode.line,
  style: const TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.w400),
  trimLines: 2,
  colorClickableText: Colors.blue,
  linkStyle: TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
)

带有 URL 的文本示例

你可以使用 linkStylelinkPattern 参数来自定义链接和其他匹配模式的外观。linkStyle 参数默认应用于 URL 和电子邮件。linkPattern 参数允许你指定其他文本模式。

ReadMoreText(
  "The Dart ecosystem uses packages to manage shared software such as libraries and tools. To get Dart packages, you use the pub package manager. You can find publicly available packages on the https://pub.dev , or you can load packages from the local file system or elsewhere",
  trimCollapsedText: 'Show more',
  trimExpandedText: 'Show less',
  trimMode: TrimMode.line,
  trimLines: 2,
  colorClickableText: Colors.blue,
  linkPattern: r'((https?://)|(www\.))([^\s/$.?#].\s*)',
  style: const TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.w400),
  moreStyle: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w400),
  lessStyle: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w400),
  linkStyle: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
  onLinkClicked: (value) { print("clicked link $value"); }
)

带有 URL 和超链接的文本示例

你可以将普通链接格式化为文本样式链接,这看起来更优雅,同时仍然保持其作为可点击链接的功能。hyperLinkMaps 参数适用于带有文本的链接映射。

ReadMoreText(
  "I have developed a Flutter package that offers a https://pub.dev/packages/read_more_text_url text expansion widget. This package includes advanced features such as URL and email detection, custom link styling, dynamic pattern matching, and the ability to add click actions on links. You can also check out an example here https://pub.dev/packages/read_more_text_url/example to see it in action.",
  trimCollapsedText: 'Show more',
  trimExpandedText: 'Show less',
  trimMode: TrimMode.line,
  trimLines: 3,
  colorClickableText: Colors.blue,
  linkPattern: r'((https?://)|(www\.))([^\s/$.?#].\s*)',
  style: const TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.w400),
  moreStyle: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w400),
  lessStyle: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w400),
  linkStyle: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
  onLinkClicked: (value) { print("clicked link $value"); },
  hyperLinkMaps: const [
    {"https://pub.dev/packages/read_more_text_url": "Read More/Read Less"}
  ]
)

示例代码

以下是完整的示例代码,展示了如何在 Flutter 应用中使用 read_more_text_url 包:

import 'package:flutter/material.dart';
import 'package:read_more_text_url/read_more_text.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Read More',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Read More Text With URL'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String linkText = 
    "I have developed a Flutter package that offers a https://pub.dev/packages/read_more_text_url text expansion widget. This package includes advanced features such as URL and email detection, custom link styling, dynamic pattern matching, and the ability to add click actions on links. You can also check out an example here https://pub.dev/packages/read_more_text_url/example to see it in action.";
  String normalText = 
    "I have developed a Flutter package that offers a Read More/Read Less text expansion widget. This package comes with several advanced features, including the ability to detect URLs and emails, custom link styling, dynamic pattern matching, and support for click actions on links.";

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Center(
              child: ReadMoreText(
                linkText,
                trimMode: TrimMode.line,
                trimLines: 2,
                style: const TextStyle(fontSize: 18),
                moreStyle: const TextStyle(
                    color: Colors.blue, fontWeight: FontWeight.w400),
                lessStyle: const TextStyle(
                    color: Colors.blue, fontWeight: FontWeight.w400),
                linkStyle: const TextStyle(
                  color: Colors.blue,
                  decoration: TextDecoration.underline,
                  decorationColor: Colors.blue,
                ),
                hyperLinkMaps: const [
                  {
                    "https://pub.dev/packages/read_more_text_url": "Read More/Read Less"
                  }
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter文本展示与URL点击插件read_more_text_url的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文本展示与URL点击插件read_more_text_url的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,read_more_text_url 是一个非常实用的插件,它允许你在文本内容中展示可点击的链接,并且支持“阅读更多”和“收起”功能。这个插件非常适合需要在有限空间内展示长文本,并且包含可点击链接的场景。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 read_more_text_url 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  read_more_text_url: ^1.0.0  # 请查看最新版本

然后运行 flutter pub get 来安装插件。

使用插件

以下是一个简单的示例,展示如何在 Flutter 应用中使用 read_more_text_url 插件:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Read More Text with URL Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: ReadMoreTextUrl(
            'This is a long text with a link to https://flutter.dev and another link to https://pub.dev. You can click on these links to open them in the browser. This text will be truncated if it exceeds the specified number of lines.',
            numLines: 2, // 设置文本显示的最大行数
            style: TextStyle(fontSize: 16.0, color: Colors.black), // 文本样式
            linkStyle: TextStyle(fontSize: 16.0, color: Colors.blue), // 链接样式
            onLinkTap: (url) {
              print('Link clicked: $url');
              // 你可以在这里处理链接点击事件,比如打开浏览器
            },
            trimMode: TrimMode.Line, // 裁剪模式
            trimCollapsedText: '...Read more', // “阅读更多”文本
            trimExpandedText: ' Less', // “收起”文本
          ),
        ),
      ),
    );
  }
}

参数说明

  • text: 要显示的文本内容。
  • numLines: 文本显示的最大行数,超过这个行数后文本会被截断。
  • style: 文本的样式。
  • linkStyle: 链接的样式。
  • onLinkTap: 当链接被点击时的回调函数,参数为链接的 URL。
  • trimMode: 裁剪模式,可以是 TrimMode.LineTrimMode.Length
  • trimCollapsedText: 当文本被截断时显示的“阅读更多”文本。
  • trimExpandedText: 当文本展开时显示的“收起”文本。

处理链接点击

onLinkTap 回调中,你可以处理链接的点击事件。例如,你可以使用 url_launcher 插件来在浏览器中打开链接:

import 'package:url_launcher/url_launcher.dart';

onLinkTap: (url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}
回到顶部