美文网首页
Flutter:webview_flutter加载本地html文

Flutter:webview_flutter加载本地html文

作者: 言溪Lee | 来源:发表于2020-04-09 18:55 被阅读0次
    • html文件放置

    首先,将.html文件拖进工程,我是放在最外级目录,和pubspec.yaml同级;
    然后,打开pubspec.yaml,在 assets: 下添加该文件,如:

    assets:
      - membership_agreement.html
    
    • 加载本地html文件
    import 'package:flutter/services.dart' show rootBundle;
    //读取文件
    Future<String> _getFile() async {
      //此html即为文件名'membership_agreement.html'
      return await rootBundle.loadString(widget.html);
    }
    //读取html数据
    body: FutureBuilder<String>(
      future: _getFile(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
           //注意:数据处理这里,一定要设置encoding不然读出来就是一堆火星文
           final String htmlUrl = Uri.dataFromString(snapshot.data, mimeType: 'text/html', encoding: Encoding.getByName('utf-8'), base64: true).toString();
           return _buildWeb(htmlUrl);
         }
         return EmptyView('读取失败');
      })
    
    const String kNavigationExamplePage = '''
    <!DOCTYPE html><html>
    <head><title>Navigation Delegate Example</title></head>
    <body>
    <p>
    The navigation delegate is set to block navigation to the youtube website.
    </p>
    <ul>
    <ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
    <ul><a href="https://www.google.cn/">https://www.google.cn/</a></ul>
    </ul>
    </body>
    </html>
    ''';
    
    void _onNavigationDelegateExample(
          WebViewController controller, BuildContext context) async {
        //不能用这种方式处理snapshot.data,报错:contains Invalid Characters,没弄明白 
        final String contentBase64 =
            base64Encode(const Utf8Encoder().convert(kNavigationExamplePage));
        await controller.loadUrl('data:text/html;base64,$contentBase64');
      }
    
    

    相关文章

      网友评论

          本文标题:Flutter:webview_flutter加载本地html文

          本文链接:https://www.haomeiwen.com/subject/nbchmhtx.html