flutter加载WebView,alert弹窗失效,evaluateJavascript方法失效

flutter加载WebView,alert弹窗失效,evaluateJavascript方法失效

  • 说明
    • 报错信息
    • 解决方案
    • 建议flutter_webView写法

说明

在APP的根页面加载webview,里面的evaluateJavascript方法失效,alert交互弹窗失效。

报错信息

E/flutter (18386): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method evaluateJavascript on channel plugins.flutter.io/webview_0)
E/flutter (18386): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:157:7)
E/flutter (18386): <asynchronous suspension>
E/flutter (18386): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:332:12)
E/flutter (18386): #2      MethodChannelWebViewPlatform.evaluateJavascript (package:webview_flutter/src/webview_method_channel.dart:118:21)
E/flutter (18386): #3      WebViewController.evaluateJavascript (package:webview_flutter/webview_flutter.dart:746:39)
E/flutter (18386): #4      _SmartPortalPageState._coordinate.<anonymous closure>.<anonymous closure> (package:bop/pages/smart_portal/smart_portal.dart:214:25)
E/flutter (18386): #5      _rootRun (dart:async/zone.dart:1182:47)
E/flutter (18386): #6      _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (18386): #7      _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (18386): #8      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (18386): #9      _rootRun (dart:async/zone.dart:1190:13)
E/flutter (18386): #10     _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (18386): #11     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter (18386): #12     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (18386): #13     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter (18386): #14     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter (18386): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

解决方案

在页面初始化化的时候,添加以下代码

if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();

建议flutter_webView写法

Please add below in ‘pubspec.yaml’: 
webview_flutter: ^0.3.7
oktoast: ^3.0.0

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:oktoast/oktoast.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return OKToast(
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: WebViewPage(),
      ),
    );
  }
}
class WebViewPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return WebViewPageState();
  }
}
class WebViewPageState extends State<WebViewPage> {
JavascriptChannel _alertJavascriptChannel(BuildContext context) {
return JavascriptChannel(
        name: 'Toast',
        onMessageReceived: (JavascriptMessage message) {
showToast(message.message);
        });
  }
final Completer<WebViewController> _webController = Completer<WebViewController>();
@override
Widget build(BuildContext context) {
return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter WebView example'),
      ),
      body: Builder(builder: (BuildContext context) {
return WebView(
          initialUrl: 'http://xxx/xxx',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webController.complete(webViewController);
          },
          javascriptChannels: <JavascriptChannel>[
_alertJavascriptChannel(context),
          ].toSet(),
          navigationDelegate: (NavigationRequest request) {
if (request.url.startsWith('js://webview')) {
showToast('JS调用了Flutter By navigationDelegate');
print('blocking navigation to $request}');
return NavigationDecision.prevent;
            }
print('allowing navigation to $request');
return NavigationDecision.navigate;
          },
          onPageFinished: (String url) {
print('Page finished loading: $url');
          },
        );
      }),
      floatingActionButton: jsButton(),
    );
  }
Widget jsButton() {
return FutureBuilder<WebViewController>(
        future: _webController.future,
        builder: (BuildContext context,
AsyncSnapshot<WebViewController> controller) {
if (controller.hasData) {
return FloatingActionButton(
              onPressed: () async {
                _webController.future.then((controller) {
                  controller
                      .evaluateJavascript('callJS("visible")')
                      .then((result) {});
                });
              },
              child: Text('call JS'),
            );
          }
return Container();
        });
  }
}

你可能感兴趣的:(Flutter,笔记,flutter,android,ios,webview)