I want to render a local HTML file stored in my phone memory in webview using flutter and dart.
This package is designed with simplicity in mind. Originally created to allow basic rendering of HTML content into the Flutter widget tree, this project has expanded to include support for basic styling as well!
I am using the webview_flutter plugin from the Flutter Team.
Add the dependency to pubspec.yaml:
dependencies: webview_flutter: ^0.3.20+2
Put an html file in the assets
folder (see this). I'll call it help.html
.
Get the html string in code and add it to the webview.
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webview_flutter/webview_flutter.dart'; class HelpScreen extends StatefulWidget { @override HelpScreenState createState() { return HelpScreenState(); } } class HelpScreenState extends State<HelpScreen> { WebViewController _controller; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Help')), body: WebView( initialUrl: 'about:blank', onWebViewCreated: (WebViewController webViewController) { _controller = webViewController; _loadHtmlFromAssets(); }, ), ); } _loadHtmlFromAssets() async { String fileText = await rootBundle.loadString('assets/help.html'); _controller.loadUrl( Uri.dataFromString( fileText, mimeType: 'text/html', encoding: Encoding.getByName('utf-8') ).toString()); } }
io.flutter.embedded_views_preview
as true
in the Info.plist file. Check the docs for any update on this requirement.You can pass a data URI
Uri.dataFromString('<html><body>hello world</body></html>', mimeType: 'text/html').toString()
or you can launch a web server inside Flutter and pass an URL that points to the IP/port the server serves the file from.
See also the discussion in https://github.com/fluttercommunity/flutter_webview_plugin/issues/23
See https://flutter.io/docs/development/ui/assets-and-images#loading-text-assets about how to load a string from assets.
See https://flutter.io/docs/cookbook/persistence/reading-writing-files for how to read other files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With