How to render a local HTML file with flutter dart webview

后端 未结 8 1992
孤城傲影
孤城傲影 2020-12-02 18:48

I want to render a local HTML file stored in my phone memory in webview using flutter and dart.

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 19:34

    I am using the webview_flutter plugin from the Flutter Team.

    Steps

    1. Add the dependency to pubspec.yaml:

      dependencies:
        webview_flutter: ^0.3.20+2
      
    2. Put an html file in the assets folder (see this). I'll call it help.html.

    3. 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 {
        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());
        }
      }
      

    Notes:

    • I needed to set the encoding to UTF-8 because I was getting a crash for non-ASCII characters.
    • In iOS you need to add the key io.flutter.embedded_views_preview as true in the Info.plist file. Check the docs for any update on this requirement.

    See also

    • The Power of WebViews in Flutter

提交回复
热议问题