Flutter文本折叠展开插件read_morex的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter文本折叠展开插件read_morex的使用

read_morex 插件是一个用于管理长文本显示的 Flutter 小部件。它允许用户通过点击“阅读更多”按钮来展开或折叠文本。该插件支持设置最大行数和最大长度,并且当内容超过这些限制时,会提供一个“阅读更多”链接,用户可以点击该链接查看完整内容,也可以点击“收起”链接将文本折叠回较短版本。此外,你还可以使用正则表达式应用自定义文本过滤器,以高亮或修改文本中的特定模式。

示例截图

安装

pubspec.yaml 文件中添加以下依赖项:

dependencies:
  read_morex: ^1.1.0

添加完依赖后,运行 flutter pub get 命令以获取该包。

使用方法

导入 read_morex 包
import 'package:read_morex/read_morex.dart';
在布局中使用 ReadMoreX 小部件
示例1:简单的读取更多功能
ReadMoreX(
    'This is a very long text. You can tap the "Read More" button to see more text. Suspendisse interdum consectetur libero id faucibus nisl tincidunt eget nullam. Eu nisl nunc mi ipsum faucibus vitae aliquet nec.',
    textStyle: const TextStyle(fontSize: 18),
    readMoreColor: Colors.green,
    fontWeightLabel: FontWeight.normal,
),
示例2:带过滤功能的读取更多功能
ReadMoreX(
    'Link: https://github.com/tro1d\nAlternative link: https://flutter.dev\nEmail: readmorex@demo.com\nPhone: 0808080889',
    textStyle: const TextStyle(fontSize: 18),
    readMoreColor: Colors.green,
    filterContent: true,
    fontWeightLabel: FontWeight.normal,
    customFilter: [
        ReadMoreXPattern(
            pattern: r'github.com', // 敏感 https://
            valueChanged: (value) => value?.replaceFirst('https://github.com/', 'Github '),
            onTap: (value) {
                ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('This Link $value')),
                );
            },
        ),
        ReadMoreXPattern(
            pattern: r'https://', // 敏感 https:// ,在 github.com 之后
            onTap: (value) {
                ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('This Link $value')),
                );
            },
        ),
        ReadMoreXPattern(
            pattern: r'\b[0-9]{9,}\b',
            colorChanged: Colors.red,
            onTap: (value) {
                ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('This Number $value')),
                );
            },
        ),
        ReadMoreXPattern(
            pattern: r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
            colorChanged: Colors.deepPurple,
            onTap: (value) {
                ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('This Email $value')),
                );
            },
        ),
    ],
),

完整示例

完整的示例代码可以在以下链接中找到:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:read_morex/read_morex.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(colorSchemeSeed: Colors.green),
      home: Scaffold(
        appBar: AppBar(title: const Text('Read MoreX Example')),
        body: const Padding(
          padding: EdgeInsets.symmetric(vertical: 16.0),
          child: SingleChildScrollView(
            child: Column(
              children: [
                PostCard(
                  userName: 'Read More',
                  content:
                      'This is a very long text. You can tap the "Read More" button to see more text. Suspendisse interdum consectetur libero id faucibus nisl tincidunt eget nullam. Eu nisl nunc mi ipsum faucibus vitae aliquet nec. Suspendisse interdum consectetur libero id faucibus nisl tincidunt eget nullam. Eu nisl nunc mi ipsum faucibus vitae aliquet nec.',
                ),
                PostCard(
                  userName: 'Read More with Filter',
                  content:
                      'Link: https://github.com/tro1d\nAlternative link: https://flutter.dev\nEmail: readmorex@demo.com\nPhone: 0808080889',
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class PostCard extends StatelessWidget {
  const PostCard({super.key, required this.userName, required this.content});

  final String userName;
  final String content;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green.shade50,
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      margin: const EdgeInsets.only(bottom: 4),
      child: Column(
        children: [
          Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(26),
                child: const Icon(CupertinoIcons.person_alt),
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 6.0),
                  child: Text(userName, style: const TextStyle(fontWeight: FontWeight.w600)),
                ),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 6.0),
                child: Text('4 minutes ago', style: TextStyle(fontSize: 10, color: Colors.black45)),
              ),
              const Icon(Icons.more_horiz_rounded)
            ],
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: Column(
              children: [
                Align(
                  alignment: Alignment.centerLeft,
                  child: ReadMoreX(
                    content,
                    textStyle: const TextStyle(fontSize: 18),
                    readMoreColor: Colors.green,
                    filterContent: true,
                    fontWeightLabel: FontWeight.normal,
                    customFilter: [
                      ReadMoreXPattern(
                        pattern: r'github.com',
                        valueChanged: (value) => value?.replaceFirst('https://github.com/', 'Github '),
                        onTap: (value) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('This Number $value')),
                          );
                        },
                      ),
                      ReadMoreXPattern(
                        pattern: r'https://',
                        onTap: (value) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('This Link $value')),
                          );
                        },
                      ),
                      ReadMoreXPattern(
                        pattern: r'\b[0-9]{9,}\b',
                        colorChanged: Colors.red,
                        onTap: (value) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('This Number $value')),
                          );
                        },
                      ),
                      ReadMoreXPattern(
                        pattern: r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
                        colorChanged: Colors.deepPurple,
                        onTap: (value) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('This Email $value')),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const Align(
            alignment: Alignment.centerLeft,
            child: Text.rich(
              TextSpan(
                children: [
                  TextSpan(text: 'Liked by '),
                  TextSpan(text: 'You ', style: TextStyle(fontWeight: FontWeight.w600)),
                  TextSpan(text: 'and '),
                  TextSpan(
                    text: '99 Others',
                    style: TextStyle(fontWeight: FontWeight.w600),
                  ),
                ],
              ),
            ),
          ),
          const Row(
            children: [
              Icon(CupertinoIcons.ellipses_bubble, size: 20),
              SizedBox(width: 8),
              Icon(
                CupertinoIcons.heart_fill,
                color: Colors.green,
                size: 22,
              ),
              SizedBox(width: 8),
              Icon(Icons.send_rounded, size: 20),
              Expanded(
                child: Text(
                  '63 Comments',
                  textAlign: TextAlign.end,
                ),
              ),
            ],
          ),
          const Divider(),
        ],
      ),
    );
  }
}

更多关于Flutter文本折叠展开插件read_morex的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文本折叠展开插件read_morex的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用read_more_x插件来实现文本折叠和展开的示例代码。read_more_x是一个非常流行的Flutter插件,用于处理长文本的折叠和展开功能。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  read_more_x: ^0.0.4  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 导入包

在你的Dart文件中导入read_more_x包:

import 'package:read_more_x/read_more_x.dart';

3. 使用ReadMoreText

下面是一个完整的示例,展示如何使用ReadMoreText小部件来实现文本的折叠和展开功能:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Read More Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String longText =
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo. Proin sodales pulvinar tempor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam fermentum, nulla luctus pharetra vulputate, felis tellus mollis orci, sed rhoncus sapien nunc eget odio. Integer sit amet orci a erat egestas imperdiet. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies ligula sed magna dictum porta.";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Read More Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ReadMoreText(
          longText,
          trimLines: 3, // 设置折叠前显示的行数
          trimMode: TrimMode.LineLength, // 按行数折叠
          colorClickableText: Colors.blue, // 点击展开/折叠按钮的颜色
          moreStyle: TextStyle(fontWeight: FontWeight.bold), // "更多" 文本样式
          lessStyle: TextStyle(fontWeight: FontWeight.bold), // "收起" 文本样式
          onMore: () {
            // 点击“更多”时的回调
            print("Read more clicked!");
          },
          onLess: () {
            // 点击“收起”时的回调
            print("Read less clicked!");
          },
        ),
      ),
    );
  }
}

解释

  1. ReadMoreText 小部件:这是read_more_x包提供的主要小部件,用于显示可折叠的文本。
  2. trimLines:设置折叠前显示的行数。在这个例子中,我们设置为3行。
  3. trimMode:设置折叠模式。在这个例子中,我们使用TrimMode.LineLength按行数折叠。
  4. colorClickableText:设置点击展开/折叠按钮的颜色。
  5. moreStylelessStyle:分别设置“更多”和“收起”文本的样式。
  6. onMoreonLess:分别是点击“更多”和“收起”时的回调函数。

这个示例展示了如何使用read_more_x插件来创建一个简单的文本折叠和展开功能。根据你的需求,你可以进一步自定义和扩展这个功能。

回到顶部