Flutter 解析文本

一个 Flutter 包,用于解析文本并根据预定义类型(如 URL、电话和电子邮件)提取部分,还支持正则表达式。

flutter_parsed_text

用法 ?

要使用此软件包,请将 flutter_parsed_text 添加到您的 pubspec.yaml 文件中作为 依赖项

import 'package:flutter_parsed_text/flutter_parsed_text.dart';

工作 ⚙️

ParsedText 可以接收这些参数和所有 RichText 参数

text: 将被解析和渲染的文本。

style: 它接受一个 TextStyle 对象作为属性,以样式化所有非链接文本对象。

parse: MatchText 对象数组 - 用于定义模式匹配的结构。

MatchText(
  type: "email", // predefined type can be any of this email, phone, url or custom
  style: TextStyle(
    color: Colors.red,
    fontSize: 24,
  ), // custom style to be applied to this matched text
  onTap: (url) {
    // do something here with passed url
  }, // callback funtion when the text is tapped on
),

您也可以这样定义一个自定义模式

MatchText(
  pattern: r"\B#+([\w]+)\b", // a custom pattern to match
  style: TextStyle(
    color: Colors.pink,
    fontSize: 24,
  ), // custom style to be applied to this matched text
  onTap: (url) async {
  // do something here with passed url
  }, // callback funtion when the text is tapped on
)

一个布尔值,显示不同的文本并向回调传递不同的文本

例如:您的字符串是 “提及 [@michel:5455345]”,其中 5455345 是该用户的 ID,将作为参数传递给回调函数,而 @michel 是界面上显示的值。用于 ID 和用户名提取的模式:/\[(@[^:]+):([^\]]+)\]/i

显示的文本将是:提及 ^^@michel^^

MatchText(
  pattern: r"\[(@[^:]+):([^\]]+)\]",
  style: TextStyle(
    color: Colors.green,
    fontSize: 24,
  ),
  // you must return a map with two keys
  // [display] - the text you want to show to the user
  // [value] - the value underneath it
  renderText: ({String str, String pattern}) {
    Map<String, String> map = Map<String, String>();
    RegExp customRegExp = RegExp(pattern);
    Match match = customRegExp.firstMatch(str);
    map['display'] = match.group(1);
    map['value'] = match.group(2);
    return map;
  },
  onTap: (url) {
    // do something here with passed url
  },
),

示例

Flutter_Parsed_Text 示例应用程序 中查找完整的示例代码。

ParsedText 小部件的一个小示例。

ParsedText(
  text:
    "[@michael:51515151] Hello this is an example of the ParsedText, links like http://www.google.com or https://# are clickable and phone number 444-555-6666 can call too. But you can also do more with this package, for example Bob will change style and David too. [email protected] And the magic number is 42! #react #react-native",
  parse: <MatchText>[
    MatchText(
      type: "email",
      style: TextStyle(
        color: Colors.red,
        fontSize: 24,
      ),
      onTap: (url) {
        launch("mailto:" + url);
      },
    ),
  ],
)

觉得这个项目有用吗?❤️

如果您觉得这个项目有用,请考虑在 Github 上给它一个 ⭐️,并通过社交媒体与您的朋友分享。

API 详情 ?

有关更多 API 详细信息,请参阅 flutter_parsed_text.dart

GitHub

https://github.com/fayeed/flutter_parsed_text