Sub6Resources / flutter_html

A Flutter widget for rendering static html as Flutter widgets (Will render over 80 different html tags!)
https://pub.dev/packages/flutter_html
MIT License
1.79k stars 860 forks source link

[QUESTION] How to custom renders? ^3.0.0-beta.1 #1297

Closed rengui-hs closed 1 year ago

rengui-hs commented 1 year ago
const htmlData = r"""
<body>
  <div
    style="display: inline"
    class="div-container"
  ></div>
  <div>
    <strong>Title Here</strong>
  </div>
</body>
""";

Just like this, if it matches, it will customize the rendering, if it does not match, it will parse normally.

Html.fromElement(customRenders: {
  (renderContext) {
    if (!tagMatcher('div').call(renderContext)) return false;

    final attributes = renderContext.tree.element?.attributes;
    final clazz = attributes?['class'];

    return clazz == 'div-container';
  }: CustomRender.widget(
    widget: (renderContext, _) => const Text('Div'),
  ),
});

A picture of a cute animal (not mandatory but encouraged)

Sub6Resources commented 1 year ago

See the Migration Guide

In this case, the migration would lead you to code that looks like this:

  Html.fromElement(
    extensions: [
      TagExtension(
        tagsToExtend: {"div"},
        builder: (extensionContext) => const Text('Div'),
      )
    ],
  ),

Although if you don't need any information from the ExtensionContext, you don't even need a builder, and you can do:

  Html.fromElement(
    extensions: [
      TagExtension(
        tagsToExtend: {"div"},
        child: const Text('Div'),
      )
    ],
  ),

Much simpler hopefully!

rengui-hs commented 1 year ago

See the Migration Guide

In this case, the migration would lead you to code that looks like this:

  Html.fromElement(
    extensions: [
      TagExtension(
        tagsToExtend: {"div"},
        builder: (extensionContext) => const Text('Div'),
      )
    ],
  ),

Although if you don't need any information from the ExtensionContext, you don't even need a builder, and you can do:

  Html.fromElement(
    extensions: [
      TagExtension(
        tagsToExtend: {"div"},
        child: const Text('Div'),
      )
    ],
  ),

Much simpler hopefully!

But I want to customize according to the class of the div, if there is no class, it will be rendered normally. Now all divs are rendered by custom.

Sub6Resources commented 1 year ago

Use builder for sure then. In the ExtensionContext argument of the builder method you can access the class names of the div and render however you'd like.

Sub6Resources commented 1 year ago

I think I misunderstood your code and question, my apologies. You'll want to use a MatcherExtension