Skip to content

Repository files navigation

pub packageGitHub starsGitHub forksGitHub licenseGitHub issues

Language: English | 中文


Hypertext is a highly extensible rich text widget that automatically parses styles.

Preview

View online demo

ENZH

Features

  1. Built-in support for common HTML-like tags, such as:

    • Links (with tap and long-press events)
    • Images
    • Text styles: italic, bold, strikethrough, underline, text color, gradients, etc.
    • ...
  2. Event handling support

  3. Custom markup support

  4. Customize color or style name mapping to easily support multi-theme scenes

  5. Text style inheritance for WidgetSpan's inner child

Table of contents

Getting Started

dependencies:
flutter_hypertext: ^1.0.0+1
import'package:flutter_hypertext/markup.dart';
Hypertext("Hello <color=red>Hypertext</color>")

Supported Parameters

ParameterDefaultDescription
onMarkupEventReceive events like a
lowercaseAttrNametrueConvert attribute names to lowercase
lowercaseElementNametrueConvert element names to lowercase
ignoreErrorMarkupfalseIgnore erroneous tags
colorMapperkBasicCSSColorsColor name mapping (default is CSS basic colors)
styleMapperSupported style collections
markupskDefaultMarkupsSupported markup tags

Global default configuration can be set via HypertextThemeExtension

Use Cases

  1. Rich text in multiple languages
  2. Rich text with multiple themes
  3. Highlighting keywords (search, mentions, topics...)

Predefined Markup Tags

1) LinkMarkup

Marks a range as a hyperlink, specifically for adding click events.

Tag Name: a

Parameters:

ParameterValueRequiredDescription
hrefURI stringURI
tap-☑️Handle click (can also specify long-press)
long-press-☑️Handle long press (can also specify tap)
titleString☑️Tooltip content
cursorbasicclicktextdefer...☑️See [SystemMouseCursors]
alignmentbaselinemiddletopbottom...☑️See [PlaceholderAlignment]
baselinealphabeticideographic☑️See [TextBaseline]

Example:

<ahref="https://example.com">go</a><ahref="app://op" custom-attr=footitle="User Foo" long-presstap>foo</a><!-- Supports both tap and long-press -->
Hypertext(
text,
onMarkupEvent: (MarkupEvent event){
// event.tag// event.data
},
);

2) StyleMarkup

Sets text styles for a specified range, such as text color, background color, font size, font family, font weight, italic, text decorations (underline, overline, strikethrough)...

Tag: style

Parameters:

ParameterValueRequiredDescription
colorHex Color or Color Name☑️Text color, default supports CSS Basic Colors[kBasicCSSColors]
backgroundHex Color or Color Name☑️Text background color
sizedouble☑️Text size
font-familyfont family name☑️Font family
weight100~900boldnormal☑️See [FontWeight]
font-stylenormalitalic☑️Font style [FontStyle]
decornoneunderlineoverlinelineThrough☑️Text decoration [TextDecoration]
decor-styledoubledasheddottedsolidwavy☑️Decoration style [TextDecorationStyle]
decor-colorHex Color or Color Name☑️Decoration color
thicknessdouble☑️Decoration line thickness

Example:

<stylecolor=redbackground=whitesize=20weight=900>hypertext</style><styledecor=underlinedecor-color=#F00thickness=2>hypertext</style>

StyleMarkup is a superset of the following tags:

1. FontWeightMarkup

Tag: weight

ParameterValueRequiredDescription
weight (simplify)100~900boldnormal✅️See [FontWeight]

Example:

<weight=500>foo</weight><weightweight=100>bar</weight>

2. BoldMarkup

Tags: bboldstrong

ParameterValueRequiredDescription
weight (simplify)100~900boldnormal✅️See [FontWeight]
<b>Hypertext</b><bold=900>Hypertext</bold><strongweight=100>Hypertext</strong>

3. FontStyleMarkup

Tag: font-style

ParameterValueRequiredDescription
font-style (simplify)normalitalicSee [FontWeight]

Example:

<font-style=italic>foo</font-style><font-stylefont-style=normal>bar</font-style>

4. ItalicMarkup

Tag: i

Example:

<i>bar</i>

5. TextDecorationMarkup

Tag: text-decor

ParameterValueRequiredDescription
decor (simplify)noneunderlineoverlinelineThroughText decoration [TextDecoration]
styledoubledasheddottedsolidwavy☑️Decoration style [TextDecorationStyle]
colorHex Color or Color Name☑️Decoration color
thicknessdouble☑️Decoration line thickness

Example:

<text-decor=underline style=dotted>foo</text-decor><text-decordecor=lineThroughcolor=redthickness=2>bar</text-decor>

6. DelMarkup

Tag: del

ParameterValueRequiredDescription
styledoubledasheddottedsolidwavy☑️Decoration style [TextDecorationStyle]
colorHex Color or Color Name☑️Decoration color
thicknessdouble☑️Decoration line thickness

Example:

<delcolor=red>bar</del>

7. UnderlineMarkup

Tag: uins

ParameterValueRequiredDescription
styledoubledasheddottedsolidwavy☑️Decoration style [TextDecorationStyle]
colorHex Color or Color Name☑️Decoration color
thicknessdouble☑️Decoration line thickness

Example:

<ustyle=wavy>bar</u>

8. ColorMarkup

Tag: color

Parameters:

ParameterValueRequiredDescription
color (simplify)Hex Color or Color NameText color

Example:

<color=red>bar</color><colorcolor=#FF0>bar</color>

9. SizeMarkup

Tag: size

Parameters:

ParameterValueRequiredDescription
size (simplify)doubleText size

Example:

<size=red>bar</size><sizecolor=#FF0>bar</size>

4) GradientMarkup

Sets a linear gradient for the specified range of text.

Tag: gradient

Parameters:

ParameterValueRequiredDescription
colorsHex Color or Color NameGradient colors
stopsList☑️Values between 0.0 and 1.0 for gradient stops [LinearGradient]
rotationAngle (0~360)☑️Rotation angle for gradient
tile-modeclamp (default) repeatedmirrordecal☑️Tiling mode
alignmentbaselinemiddletopbottom...☑️See [PlaceholderAlignment]
baselinealphabeticideographic☑️See [TextBaseline]

Example:

<gradientcolors="red, green" rotation=45>bar</gradient><gradientcolors="#F00,#00F" rotation=45>bar</gradient>

5) ImageMarkup

Add image, support custom parsing src and creating image widgets through imageBuilder.

[Note] The default implementation of network image is NetworkImage, which does not support disk caching. If necessary, please use ImageMarkup.imagebuilder.

Tag: imgimage

Parameters:

ParameterValueRequiredDescription
srcURI stringImage path (supports http[s]://, asset://, path)
sizeList<double>☑️Image width and height (1~2 values)
widthdouble☑️Image width
heightdouble☑️Image height
colorHex Color or Color Name☑️Colorize the picture
fitfillcontaincoverfitWidthfitHeightnonescaleDown☑️BoxFit modes
aligntopLeftcenterbottomLeft...☑️Alignment options
alignmentbaselinemiddletopbottom...☑️See [PlaceholderAlignment]
baselinealphabeticideographic☑️See [TextBaseline]

Example:

<imgsrc="https://example.com/avatar.png" size=50fit=covercolor=orange/><imgsrc="asset://images/icon.png" size="50,100"/><imgsrc="path/to/icon.png" width="50" height="50"/><!--File path-->

6) GapMarkup

Adds space gaps.

Tag: gap

Parameters:

ParameterValueRequiredDescription
gap (simplify)doubleGap size

Example:

<gap=10 /><gapgap="50"/>

7) PaddingMarkup

Adds padding inside an element.

Tag: padding

Parameters:

ParameterValueRequiredDescription
padding (simplify)doublePadding value (1~4 values)
horList<double>☑️Horizontal padding (1~2 values)
verList<double>☑️Vertical padding (1~2 values)
alignmentbaselinemiddletopbottom...☑️See [PlaceholderAlignment]
baselinealphabeticideographic☑️See [TextBaseline]

Example:

<padding="10, 20">foo</padding><!-- Set top/bottom padding to 10, left/right padding to 20 --><paddingpadding="50"/><!-- Set all padding to 50 --><paddinghor="10, 20"/><!-- Set left padding to 10, right padding to 20 --><paddingver="20"/><!-- Set vertical padding to 20 -->

6) PatternMarkup

A pattern-matching-based markup, used for recognizing and styling specific patterns such as user mentions (@foo), topics (#flutter), and email addresses (foo@bar.com).

You can define custom pattern markups by extending PatternMarkup or DefaultPatternMarkup.

Public Constructor Parameters:

Parameter NameTypeRequiredDescription
styleTextStyle✅️The text style to apply to the matched pattern.
patternString✅️The regular expression string used for pattern matching.
tagString✅️The corresponding tag name in the lexical tree.
startCharacterint☑️The starting matching character (used to reduce the number of regex matches).
enableLongPressbool☑️Whether to enable the long-press event.
enableTapbool☑️Whether to enable the tap (click) event.
cursorMouseCursor☑️The mouse cursor style when hovering over the pattern.
tooltipString☑️The tooltip text displayed on mouse hover.
alignmentPlaceholderAlignment☑️The alignment of the inline placeholder.
baselineTextBaseline☑️The text baseline for the inline placeholder.

Predefined Pattern Markups:

Warning

Using pattern markups may result in slower performance compared to not using them. The default predefined markups are not automatically added to Hypertext and must be added manually (via Hypertext.markups or HypertextThemeExtension.markups).

MarkupDescriptionUsage Example
MentionMarkupMention Tag@foo
EmailMarkupEmail Address Tagfoo@bar.com
TopicMarkupTopic Tag#flutter

Advanced

Custom Markups

Defining a Custom Markup:

classCustomMarkupextendsTagMarkup {
constCustomMarkup() :super('your-tag');
@overrideHypertextSpanonMarkup(List<HypertextSpan>? children, MarkupContext ctx) {
returnHypertextTextSpan(children: children, style:TextStyle());
returnHypertextWidgetSpan(child: child);
}
}

Setting Custom Markup:

Hypertext(
text,
markups: [...kDefaultMarkups, CustomMarkup()],
)

Or

ThemeData(
extensions: [HypertextThemeExtension(markups: [...kDefaultMarkups, CustomMarkup()])],
)

Support for multiple themes

You can see an example of a theme adaptation。

1. Define color mapper

final lightColorMapper = {
'appRed': appLightRed,
'appGreen': appLightGreen,
};
final darkColorMapper = {
'appRed': appDarkRed,
'appGreen': appDarkGreen,
};

2. Define style mapper

final styleMapper = {
'myStyle':TextStyle(
fontSize:12,
decoration:TextDecoration.underline,
),
};

3. Apply to the theme

final lightHypertextThemeExt =HypertextThemeExtension(
colorMapper: lightColorMapper,
styleMapper: styleMapper,
);
final darkHypertextThemeExt =HypertextThemeExtension(
colorMapper: darkColorMapper,
styleMapper: styleMapper,
);
final lightTheme =ThemeData(extensions: [lightHypertextThemeExt]);
final darkTheme =ThemeData(extensions: [darkHypertextThemeExt]);
MaterialApp(
themeMode:ThemeMode.light,
theme: lightTheme,
darkTheme: darkTheme,
locale: settings.local,
localizationsDelegates:L.localizationsDelegates,
supportedLocales:L.supportedLocales,
home:HomePage(),
)

4. Usage

Hypertext(
"<gradient colors='appGreen,appRed' alignment=middle>Hypertext</gradient>是一个基于Flutter的<style name=myStyle>高扩展性</style>的富文本组件。"
)

Special Notes

Color Names

By default, CSS Basic Colors[kBasicCSSColors] are supported. You can customize color name mappings via Hypertext.colorMapper and HypertextThemeExtension.colorMapper.

Hex Colors

Supports the following formats:

  1. RGB, e.g., #0F0
  2. RGBA, e.g., #0F0F
  3. RRGGBB, e.g., #00FF00
  4. RRGGBBAA, e.g., #00FF00FF

Margin Values

Supports the following formats:

  1. 10left=10 top=10 right=10 bottom=10
  2. 10, 20left=20 top=10 right=20 bottom=10
  3. 10, 20, 30left=20 top=10 right=20 bottom=30
  4. 10, 20, 30, 40left=10 top=20 right=30 bottom=40

Things to Keep in Mind

  1. When customizing Markups, it is recommended to use HypertextTextSpan or HypertextWidgetSpan to help inherit styles from parent WidgetSpan for text within it.

TODO

  • ☑️ Improve selectability: Add built-in selectability options and pass selectability to WidgetSpan.

About

Hypertext is a highly extensible flutter rich text widget that automatically parses styles.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages