Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for anchor links within the same document #535

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ class _MyHomePageState extends State<MyHomePage> {
title: Text('flutter_html Example'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Html.scrollToTop();
},
child: Icon(Icons.expand_less)
),
body: SingleChildScrollView(
child: Html(
data: htmlData,
Expand Down
28 changes: 28 additions & 0 deletions lib/flutter_html.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
library flutter_html;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_html/html_parser.dart';
import 'package:flutter_html/image_render.dart';
import 'package:flutter_html/style.dart';
Expand Down Expand Up @@ -69,6 +70,33 @@ class Html extends StatelessWidget {
/// to use NavigationDelegate.
final NavigationDelegate navigationDelegateForIframe;

/// Scrolls the HTML widget to the top.
/// You can set the duration and curve to use, by default the duration is 100ms and the curve is [Curves.easeIn]
/// This method should not be called until the widget is fully built.
static void scrollToTop({Duration duration, Curves curve}) {
final context = scrollContext;
final renderObject = context.findRenderObject();
if (renderObject == null) return;

final offsetToReveal = RenderAbstractViewport.of(renderObject)
?.getOffsetToReveal(renderObject, 0.0)
?.offset;
final position = Scrollable.of(scrollContext)?.position;
if (offsetToReveal == null || position == null) return;

final alignment = (position.pixels > offsetToReveal)
? 0.0
: (position.pixels < offsetToReveal ? 1.0 : null);
if (alignment == null) return;

position.ensureVisible(
renderObject,
alignment: alignment,
duration: duration ?? const Duration(milliseconds: 100),
curve: curve ?? Curves.easeIn,
);
}

@override
Widget build(BuildContext context) {
final double width = shrinkWrap ? null : MediaQuery.of(context).size.width;
Expand Down
Loading