/
html_view.dart
78 lines (72 loc) · 2.09 KB
/
html_view.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:git_touch/utils/utils.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HtmlView extends StatefulWidget {
final String html;
HtmlView(String text, {String cssText, List<String> cssLinks = const []})
: html = '<meta name="viewport" content="width=device-width">' +
cssLinks
.map((link) =>
'<link rel="stylesheet" href="$link" crossorigin="anonymous" />')
.join('') +
'<style>body{margin:12px}${cssText ?? ''}</style>' +
text;
@override
_HtmlViewState createState() => _HtmlViewState();
}
class _HtmlViewState extends State<HtmlView> {
Timer timer;
double height;
WebViewController controller;
var loaded = false;
updateHeight() async {
final value = await controller
.evaluateJavascript("document.documentElement.scrollHeight;");
// print(value);
setState(() {
height = double.parse(value);
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final uri = Uri.dataFromString(
widget.html,
mimeType: 'text/html',
encoding: Encoding.getByName('utf-8'),
);
return Container(
height:
height ?? 0.01, // 0 would return the wrong height on page finished.
child: WebView(
initialUrl: uri.toString(),
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (c) async {
controller = c;
timer = Timer.periodic(Duration(milliseconds: 1000), (t) {
updateHeight();
});
},
onPageFinished: (some) async {
timer.cancel();
updateHeight();
},
navigationDelegate: (request) {
if (loaded) {
launchUrl(request.url); // TODO:
return NavigationDecision.prevent;
} else {
loaded = true;
return NavigationDecision.navigate;
}
},
),
);
}
}