How do i replicate the HTML anchor tag navigation to Jump to a Specific Part of a Page in Flutter?

80 views Asked by At

I am currently using flutter_widget_from_html_core to view html string that we got from our cms. Additionally, am using url_launcher package to open an anchor tag href.

Current approach:

HtmlWidget(
  html ?? '',
  customStylesBuilder: (element) {
  },
  customWidgetBuilder: (element) {
  },
  onErrorBuilder: (context, element, error) {
  },
  onTapUrl: (url) async {
    return launchUrlString(url);
  },
)

How can i imitate the HTML's way of jumping to a specific part of a page based on the id of the element

something like in this example here

1

There are 1 answers

0
Son Dao On

In the HtmlWidgetState class, there is a method named scrollToAnchor which allows scrolling to a specific element identified by its id, see pub.dev.

If you want to scroll as soon as the page is opened, you might consider initiating the scrolling action in the initState method. Here's how you could implement it:

class _MyState extends State<MyPage> {
  // a key for the state object that we need
  final GlobalKey<HtmlWidgetState> htmlWidget = GlobalKey();

  @override
  void initState() {
    super.initState();
    final String? target = widget.target;
    if (target != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        // wait until after the HTML content has been rendered
        // then request a scroll to the specified target
        htmlWidget.currentState?.scrollToAnchor(target);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView( // needed for long HTML
        child: Padding(
          padding: EdgeInsets.all(8.0),
          child: HtmlWidget(
            widget.html ?? '',
            key: htmlWidget, // needed to use `currentState` in our callback,
            onTapUrl: (url) async {
              return launchUrlString(url);
            },
          ),
        ),
      ),
    );
  }
}

Note that there can be issues, especially if the HTML content is extensive. In such cases, the HtmlWidget might perform asynchronous rendering, which means immediate scrolling might not be feasible. However, this general approach should give you a good starting point.