Flutter_widget_from_html: With more than one HtmlWidget on the same route, only the last onTapUrl is called

Created on 24 Sep 2020  路  4Comments  路  Source: daohoangson/flutter_widget_from_html

If I have two HtmlWidgets, each with its own onTapUrl defined, only the second one is called, even for the first HtmlWidget.

Example:

  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          HtmlWidget(
            '<a href="https://www.example.com/link_one">Link 1</a>',
            onTapUrl: (url) {
              print('CALLBACK ONE');
              print(url);
            },
          ),
          HtmlWidget(
            '<a href="https://www.example.com/link_two">Link 2</a>',
            onTapUrl: (url) {
              print('CALLBACK TWO');
              print(url);
            },
          ),
        ],
      ),
    );
  }

Clicking the first link outputs

I/flutter (16064): CALLBACK TWO
I/flutter (16064): https://www.example.com/link_one

Clicking the second link outputs

I/flutter (16064): CALLBACK TWO
I/flutter (16064): https://www.example.com/link_two

Using the same callback for both works, but I had a situation where each HtmlWidget was nested deeper in other Widgets, each with its own onTapUrl handler.

question

All 4 comments

Hmm, this happened because the default WidgetFactory is a singleton and it keeps track of the latest onTapUrl set. I'll probably remove the singleton usage since it's causing more trouble that its worth.

Meanwhile, you can workaround this by ignoring the singleton, something like this should work:

          HtmlWidget(
            '<a href="https://www.example.com/link_one">Link 1</a>',
            factoryBuilder: () => WidgetFactory(), // ignore the default factory
            onTapUrl: (url) {
              print('CALLBACK ONE');
              print(url);
            },
          ),
          HtmlWidget(
            '<a href="https://www.example.com/link_two">Link 2</a>',
            factoryBuilder: () => WidgetFactory(), // ignore the default factory
            onTapUrl: (url) {
              print('CALLBACK TWO');
              print(url);
            },
          ),

Sounds great, thank you!

v0.5.0+6 has been released with the change. You can now drop the factoryBuilder param from HtmlWidget 馃憤

Awesome, thank you!

Was this page helpful?
0 / 5 - 0 ratings