A Flutter package to parse text and make them into linkified text widget

Overview

🔗 Flutter Parsed text

A Flutter package to parse text and extract parts using predefined types like url, phone and email and also supports Regex.

Usage 💻

To use this package, add flutter_parsed_text as a dependency in your pubspec.yaml file.

import 'package:flutter_parsed_text/flutter_parsed_text.dart';

Working ⚙️

ParsedText can receive this paramters & all the RichText parameters:

text: Text that will be parsed and rendered.

style: It takes a TextStyle object as it's property to style all the non links text objects.

parse: Array of MatchText object - used for defining structure for pattern matching .

MatchText(
  type: ParsedType.EMAIL, // predefined type can be any of this ParsedTypes
  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
),

You can also define a custom pattern like this:

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
)

You can also set RegexOption for the custom regex pattern like so:

MatchText(
  pattern: r"\B#+([\w]+)\b", // a custom pattern to match
  regexOptions: RegexOptions(
    multiLine : false,
    caseSensitive : false,
    unicode : false,
    dotAll : false
  ),
  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
)

A boolean that show a diffrent text and passes a diffrent text to the callback

eg: Your str is "Mention [@michel:5455345]" where 5455345 is ID of this user which will be passed as parameter to the callback funtion and @michel the value to display on interface. Your pattern for ID & username extraction : /\[(@[^:]+):([^\]]+)\]/i

Displayed text will be : Mention ^^@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
  },
),

Example ✍🏻

Find the complete example wiring in the Flutter_Parsed_Text example application.

A small example of the ParsedText widget.

ParsedText(
  text:
    "[@michael:51515151] Hello this is an example of the ParsedText, links like http://www.google.com or http://www.facebook.com 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: ParsedType.EMAIL,
      style: TextStyle(
        color: Colors.red,
        fontSize: 24,
      ),
      onTap: (url) {
        launch("mailto:" + url);
      },
    ),
  ],
)

Found this project useful? ❤️

If you found this project useful, then please consider giving it a ⭐️ on Github and sharing it with your friends via social media.

API details 👨🏻‍💻

See the flutter_parsed_text.dart for more API details

License ⚖️

Issues and feedback 💭

If you have any suggestion for including a feature or if something doesn't work, feel free to open a Github issue for us to have a discussion on it.

Comments
  • Global regexOptions

    Global regexOptions

    In version 2.2.0 you have a breaking change (Please follow semver)

    Removed regexOptions property from MatchText and now comes with a global regexOptions property for ParsedText Widget.

    Why? I think it's totally wrong! Assume we have two MatchText , and want to set caseSensitive: false for first and caseSensitive: true for second, how is it possible with a global regexOptions?

    opened by sm2017 20
  • Phone number regex can be improved

    Phone number regex can be improved

    The regular expression used for phone numbers does not take into account escape characters that might come before the phone number. Also if a user wants to input an extension sthe regex won't work but that is less of a concern.

    opened by erickjtorres 6
  • if onTap is not provided, the TextSpan should't react to gestures

    if onTap is not provided, the TextSpan should't react to gestures

    Now it is not possible to work with ParsedText is there is no need to react to user clicks and onTap is null. Moreover, I cannot wrap ParsedText with another GestureDetector and handle other user gestures (Had to wrap with IgnorePointer)

    bug 
    opened by alectogeek 3
  • Can click event add style response?

    Can click event add style response?

    Thank you for creating this package, I really like it. I often use it to do some rich text work, it works very well. But one thing, we have some rich text that needs to be clicked, and these clicks need to match the material style to give users visual feedback. So we need to change the style of the text when we click.

    So can such a function be added?

    thx.

    enhancement 
    opened by SF-Simon 3
  • added support for overflowWidget

    added support for overflowWidget

    Needed to have support of overflowWidget for my project, specifically to support ..see more as the overflow text. Using extended_text to add this support.

    It is works in my project ✅ Please review and merge, if all is well.

    Oh yeah, pub get just upgraded some packages, do verify if they effect any.

    question 
    opened by avvari-da 2
  • maxLines bug

    maxLines bug

    if maxLines set null it's mean unlimited in flutter

    ~/flutter/packages/flutter/lib/src/widgets/basic.dart

    /// The [maxLines] property may be null (and indeed defaults to null), but if /// it is not null, it must be greater than zero.

    properties.add(IntProperty('maxLines', maxLines, ifNull: 'unlimited'));

    but in ParsedText, write like maxLines: null it's show 1 line bug ?

    ParsedText( alignment: TextAlign.start, maxLines: null, overflow: TextOverflow.ellipsis, text:

    opened by gaoyong06 2
  • onTap uses matchText instead of result['value'] when using renderText

    onTap uses matchText instead of result['value'] when using renderText

    According to the readme file in the renderText function you're supposed to return a Map with 'display' and 'value' entries where the 'value' entry is the value used. However, in the current version the 'value' entry is never even used. I can see that it was previously used but this was changed in commit f5051f5. Was this on purpose or just a slight mistake? If it was on purpose then it does not make sense to return a map from renderText since only the 'display' entry is used.

    opened by magnusrp0808 1
  • renderText argument/parameter Type mismatch

    renderText argument/parameter Type mismatch

    renderText is saying there is a type mismatch (dart(argument_type_not_assignable))even though I copied this directly from the main documentation example

    interestingly enough, everything actually works when I flutter run - no issue compiling and everything renders as expected in my iOS simulator

    I'm not able to get the error in my editor to go away no matter what I try, so figure this is some sort of issue (I just recently upgraded to flutter 2 and using version ^2.1.0 of this package)

    Screen Shot 2021-03-25 at 9 25 14 PM
    opened by chandlerr13 1
  • Extending to TextField

    Extending to TextField

    Thanks for developing this is a great package!

    I was wondering if it's possible to add a ParsedTextField widget to this package, to cater a multiline TextField to have such styling. I am a newbie to flutter. If I can gather some information around it, will contribute.

    Just putting out the idea here for now.

    opened by avvari-da 1
  • onTap not work in matches

    onTap not work in matches

    Hello. on tap not work in matches. but if i add onTap in ParsedText it work. And i have this in code on top

    Scaffold(
            body: GestureDetector(
              behavior: HitTestBehavior.opaque,
          onTap: () {
             WidgetsBinding.instance.focusManager.primaryFocus?.unfocus();
            /*FocusScopeNode currentFocus = FocusScope.of(context);
            if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
              currentFocus.focusedChild.unfocus();
            }*/
          },
          onDoubleTap: (){
            _scrollController.animateTo(
                    _scrollController.position.maxScrollExtent,
                    curve: Curves.easeOut,
                    duration: const Duration(milliseconds: 300),
                  );
          },
          child:...
    )
    )
    

    and this parsed text

    matches = [
                        new MatchText(
                        type: ParsedType.URL,
                        style: TextStyle(
                          color: Colors.blue,
                          
                        ),
                        onTap: (url) async {
                          print(url);
                          var a = await canLaunch(url);
    
                          if (a) {
                            launch(url);
                          }
                          
                        }),
                        new MatchText(
                        type: ParsedType.PHONE,
                        style: TextStyle(
                          color: Colors.purple,
                          
                        ),
                        onTap: (url) {
                          launch("tel:" + url);
                        }),
                      ];
    
    ParsedText(
                      alignment: TextAlign.start,
                      selectable: true,
                      text: message,
                      parse:matches,
                      onTap: () {print("Text Tap Tap Tap");},
                    )
    
    opened by Alexfuse 1
  • Editable ParsedText

    Editable ParsedText

    Is it possible to make ParsedText optionally editable, like with a boolean? I understand RichText doesn't allow for it, since there's preset spans with fixed portions of texts and textstyles, but it makes sense conceptually for parsed text, where the spans are built by matching the text, thus in a case of the text being edited, simply reparse it with the changes.

    Programmatically, might be difficult to implement though. Is this a possible feature or would it require too much of an overhaul? Thanks either way!

    opened by Addictorator 1
  • Selecte and copy CUSTOM widgetSpan then paste the text is an unknown character of an obj.

    Selecte and copy CUSTOM widgetSpan then paste the text is an unknown character of an obj.

    I add a MatchText to ParsedText's parse. but I want copy it. but cant't copy text from renderWidget.

    return MatchText(
            pattern: TextEntity.emoPattern.pattern,
            renderWidget: ({text, pattern}) {
              Widget child = Text('$text ');
              if (text.startsWith('[') && text.endsWith(']') && text.length >= 3) {
                final content =
                    text.substring(1, text.length - 1).replaceAll(nullChar, '');
    
                if (EmoUtil.instance.allEmoMap[content] != null) {
                  final Widget emoji =
                      EmoUtil.instance.getEmoIcon(content, size: fontSize);
    
                  child = Padding(
                    padding: fontSize == 48
                        ? const EdgeInsets.fromLTRB(2, 4, 2, 4)
                        : const EdgeInsets.fromLTRB(2, 2, 2, 2),
                    child: emoji,
                  );
                }
              }
              return child;
            });
    

    https://user-images.githubusercontent.com/15946864/173023138-1ce248a5-2a8e-44a9-8d03-800f6cac7d5e.mp4

    opened by chifandeyu 2
  • Feature Request: Allow usage with Expand_widget

    Feature Request: Allow usage with Expand_widget

    I think this will be awesome to use with the expand_widget for very long text. For now, it forces the display of complete long text, how about customizing to use expand widget to show more? Screen Shot 2021-12-03 at 10 56 26 AM

    opened by ericel 0
  • Not working while trying to parse utf8 unicode data.

    Not working while trying to parse utf8 unicode data.

    I have unicode data i am trying to parse.

    I have following regex (?<=ژژ).*(?=ژژ) its working fine on regex101 as you can see following image. Capture I am using following code: ParsedText( text: ''' ژژ صفحہ نمبر 15ژژص ژ1 ’’وَلَقَدْ اَرْسَلْنَا نُوْحاً وَّاِبْرَاہِیْمَ وَجَعَلْنَافِیْ ذُرِّیَّتِہِمَاالنُّبُوَّۃَ وَالْکِتٰبَ فَمِنْہُمْ مُھْتَدٍ۔وَکَثِیْرٌ مِّنْہُمْ فٰسِقُوْنَ۔ ثُمَّ قَفَّیْنَا عَلیٰٓ اٰثَارِہِمْ بِرُسُلِنَا صژص ژ8 (حدید:۲۶،۲۷)‘‘ صژص''', style: Get.textTheme.headline6, parse: <MatchText>[ MatchText( pattern: r'(?<=ژژ).*(?=ژژ)', style: TextStyle( color: Colors.red, fontSize: 24, ), renderText: ({String str, String pattern}) { Map<String, String> map = Map<String, String>(); RegExp customRegExp = RegExp(pattern); Match match = customRegExp.firstMatch(str); map['display'] = '\n'; map['value'] = match.group(2); print(match.group(1)); print(match.group(2)); return map; }, ), ], ),

    opened by naeem-shah 0
Owner
Fayeed Pawaskar
Creator of ChartNerd | Flutter | React Native | ReactJs
Fayeed Pawaskar
A powerful extended official text for Flutter, which supports Speical Text(Image,@somebody), Custom Background, Custom overFlow, Text Selection.

Extended official text to build special text like inline image or @somebody quickly,it also support custom background,custom over flow and custom selection toolbar and handles.

FlutterCandies 509 Jan 4, 2023
Rich Text renderer that parses Contentful Rich Text JSON object and returns a renderable Flutter widget

Contentful Rich Text Renderer for Flutter Rich Text renderer that parses Contentful Rich Text field JSON output and produces a Flutter Widget tree tha

Kumanu 45 Nov 10, 2022
Flutter widget that automatically resizes text to fit perfectly within its bounds.

Flutter widget that automatically resizes text to fit perfectly within its bounds. Show some ❤️ and star the repo to support the project Resources: Do

Simon Leier 1.8k Jan 3, 2023
Arc Text Widget for Flutter

Flutter Arc Text Renders text along the arc. See demo. The story behind the plugin is here. Basic usage class MyApp extends StatelessWidget

Kirill Bubochkin 15 Oct 18, 2021
Soft and gentle rich text editing for Flutter applications.

About Zefyr Soft and gentle rich text editing for Flutter applications. You are viewing early dev preview version of this package which is no longer a

Memspace 2.2k Jan 8, 2023
Soft and gentle rich text editing for Flutter applications

Soft and gentle rich text editing for Flutter applications. Zefyrka is a fork of Zefyr package with the following improvements: support Flutter 2.0 op

null 85 Dec 21, 2022
Text Editor in Flutter for Android and iOS to help free write WYSIWYG HTML code

Flutter Summernote Text Editor in Flutter for Android and iOS to help free write WYSIWYG HTML code based on Summernote 0.8.18 javascript wrapper. NOTI

Chandra Abdul Fattah 41 Sep 12, 2022
A masked text for Flutter.

flutter_masked_text Masked text input for flutter. Alert Hi guys! Unfortunately, I'm not developing mobile anymore. This repo will not receive updates

Ben-hur Santos Ott 264 Dec 21, 2022
A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.

A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.

Bytedance Inc. 646 Dec 29, 2022
A customizable code text field supporting syntax highlighting

CodeField A customizable code text field supporting syntax highlighting Live demo A live demo showcasing a few language / themes combinaisons Showcase

Bertrand 162 Dec 23, 2022
Statistics Dart package for easy and efficient data manipulation with many built-in functions and units.

statistics Statistics package for easy and efficient data manipulation with many built-in mathematical functions and units. Usage Numeric extension: i

Graciliano Monteiro Passos 13 Nov 7, 2022
A Flutter Package to render Mathematics, Physics and Chemistry Equations based on LaTeX

flutter_tex Contents About Demo Video Screenshots How to use? Android iOS Web Examples Quick Example TeXView Document TeXView Markdown TeXView Quiz Te

Shahzad Akram 219 Jan 5, 2023
A Flutter package provides some implementations of TextInputFormatter that format input with pre-defined patterns

A Flutter package provides some implementations of TextInputFormatter that format input with pre-defined patterns

HungHD 192 Dec 31, 2022
Flutter textfield validation lets you validate different textform fields in your Flutter app

Flutter textfield validation lets you validate different textform fields in your Flutter app

World-Package 2 Sep 15, 2022
A markdown renderer for Flutter.

Flutter Markdown A markdown renderer for Flutter. It supports the original format, but no inline HTML. Overview The flutter_markdown package renders M

Flutter 828 Aug 12, 2021
flutter 中文排版,支持分页上下对齐 两端对齐 翻页动画

text_composition flutter 中文排版 分页 上下对齐 两端对齐 多栏布局 弃用richText,使用Canvas,精确定位绘图位置,消除字体对排版影响 视频与截图 demo https://github.com/mabDc/text_composition/releases/t

西红柿大芝麻 50 Nov 3, 2022
Flutter Tutorial - PDF Viewer - Asset, File, Network & Firebase

Flutter Tutorial - PDF Viewer - Asset, File, Network & Firebase Use the Flutter PDF Viewer to download PDF documents and display them within your Flut

Johannes Milke 36 Dec 9, 2022
Create an AutoComplete TextField to search JSON data based on suggestions in Flutter.

Flutter Tutorial - AutoComplete TextField & AutoComplete Search Create an AutoComplete TextField to search JSON data based on suggestions in Flutter.

Johannes Milke 32 Oct 23, 2022
Flutter phone number input

phone_form_field Flutter phone input integrated with flutter internationalization Features Totally cross platform, this is a dart only package / depen

cedvdb 38 Dec 31, 2022