Flutter-如何在WebViewScaffold中加载本地HTML文件?

时间:2020-07-02 14:53:55

标签: flutter dart webview

我正在尝试在WebViewScaffold中加载本地HTML文件,但是我没有插件onWebViewCreated提供的webview_flutter的回调。我不能使用这种依赖关系,因为我想访问webview_flutter不提供的Webview回调的状态侦听器。谁能告诉我如何加载本地文件? 这是我当前的实现-

   final Set<JavascriptChannel> jsChannels = [
      JavascriptChannel(
          name: 'Print',
          onMessageReceived: (JavascriptMessage message) {
            print(message.message);
          }),
    ].toSet();
    
    void main() {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      final flutterWebViewPlugin = FlutterWebviewPlugin();
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter WebView Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          routes: {
            '/': (_) => const MyHomePage(),
            '/widget': (_) {
              return WebviewScaffold(
                url: selectedUrl,  // How to load a local file here?
                javascriptChannels: jsChannels,
                mediaPlaybackRequiresUserGesture: false,
                appBar: AppBar(
                  title: const Text('Widget WebView'),
                ),
                withZoom: true,
                withLocalStorage: true,
                hidden: true,
                initialChild: Container(
                  color: Colors.redAccent,
                  child: const Center(
                    child: Text('Waiting.....'),
                  ),
                ),
            },
          },
        );
      }
    }

1 个答案:

答案 0 :(得分:2)

您可以像下面这样从用户的电话加载本地HTML文件:

...
url: Uri.dataFromString(
    File('filePath').readAsStringSync(),
    mimeType: 'text/html',
).toString(),
...

,如果您想从应用程序包中打开一个html文件(资产文件夹中的html文件),则可以这样做:

...
url: Uri.dataFromString(
    await rootBundle.loadString('assets/index.html'),
    mimeType: 'text/html',
).toString(),
...

注意:您必须像其他任何资产一样在pubspec.yaml资产部分中声明html文件。