Flutter:webview_flutter加载本地html文件

  • html文件放置

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

assets:
  - membership_agreement.html
  • 加载本地html文件
import 'package:flutter/services.dart' show rootBundle;
//读取文件
Future _getFile() async {
  //此html即为文件名'membership_agreement.html'
  return await rootBundle.loadString(widget.html);
}
//读取html数据
body: FutureBuilder(
  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 = '''

Navigation Delegate Example

The navigation delegate is set to block navigation to the youtube website.

''';
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文件)