Flutter html text style

Flutter HTML Text Style

In Flutter, you can use HTML-like tags to style and format your text using the flutter_html package. This package allows you to render HTML content with support for various text styling options.

To use the flutter_html package, you will first need to add it as a dependency in your pubspec.yaml file:

dependencies:
   flutter_html: ^2.0.0

After adding the dependency, you can import the package in your Dart file:

import 'package:flutter_html/flutter_html.dart';

Basic Usage

To render HTML content with the desired text styles, you can wrap the HTML string inside a Html widget provided by the flutter_html package. Here’s an example:

Html(
      data: "

Heading 1

This is a paragraph.

", )

This will render the HTML content with default text styles. You can customize the text styles by applying CSS-like inline styles or using CSS classes.

Applying Inline Styles

You can apply inline styles to your HTML content using the style attribute. Here’s an example:

Html(
      data: "

Blue Heading

", )

This will render the heading with blue color.

Using CSS Classes

If you have defined CSS classes for your text styles, you can apply them to the HTML content using the customTextStyle property of the Html widget. Here’s an example:

Html(
      data: "

Custom Heading

", customTextStyle: (dom.Node node, TextStyle baseStyle) { if (node is dom.Element) { switch (node.localName) { case 'h1': return baseStyle.merge(TextStyle(fontSize: 24)); } } return baseStyle; }, )

In this example, we defined a CSS class custom-heading and applied it to the <h1> tag. The customTextStyle property allows you to define a callback function that receives the HTML node and the base text style. Inside the callback, you can check for specific HTML tags and apply custom text styles as required.

Handling Clicks on Links

The flutter_html package also provides a way to handle clicks on links within the HTML content. You can use the onLinkTap property to define a callback function that will be called when a link is tapped. Here’s an example:

Html(
      data: "Click here",
      onLinkTap: (url) {
         // Handle link tap
      },
   )

In this example, when the user taps on the link, the defined callback function will be called, allowing you to handle the link tap event.

Conclusion

The flutter_html package provides a convenient way to render HTML content with various text styling options in Flutter. You can use inline styles or CSS classes to customize the text styles, and also handle clicks on links within the HTML content. With these capabilities, you can easily format and style your text in a rich and visually appealing manner.

Leave a comment