如何使用flutter dart webview渲染本地HTML文件 [英] How to render a local HTML file with flutter dart webview

查看:30
本文介绍了如何使用flutter dart webview渲染本地HTML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Flutter 和 dart 在 webview 中渲染存储在我手机内存中的本地 HTML 文件.

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

推荐答案

我正在使用 webview_flutter Flutter 团队的插件.

I am using the webview_flutter plugin from the Flutter Team.

  1. 将依赖添加到pubspec.yaml:

dependencies:
  webview_flutter: ^0.3.20+2

  • assets 文件夹中放置一个 html 文件(参见 this).我将其命名为 help.html.

  • Put an html file in the assets folder (see this). I'll call it help.html.

    获取代码中的html字符串并添加到webview中.

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

  • 注意事项:

    • 我需要将编码设置为 UTF-8,因为我遇到了非 ASCII 字符的崩溃.
    • 在 iOS 中,您需要在 Info.plist 文件中将键 io.flutter.embedded_views_preview 添加为 true.查看 docs 了解有关此要求的任何更新.
    • 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.
      • 这篇关于如何使用flutter dart webview渲染本地HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆