如何在webview flutter中触发JavaScript函数?

rqqzpn5f  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(226)

试图转换旧代码为webview插件3到4,但坚持如何将消息传输回网页.
下面是在网页中触发receivePhoto()函数的函数,但不知何故没有触发(终端显示的是jsCode)。

void _pickfile() async {
  final pickedFile = await ImagePicker().pickImage(source: ImageSource.camera);
  if (pickedFile != null) {
    final bytes = await pickedFile.readAsBytes();
    final base64 = base64Encode(bytes);
    final jsCode = "receivePhoto('$base64');";
    await WebViewController().runJavaScript(jsCode);
    print(jsCode);//this print works
  } else {
    // User canceled the picker
  }
}

这是主代码:

class WebViewApp extends StatefulWidget {
  const WebViewApp({Key? key}) : super(key: key);
  @override
  State<WebViewApp> createState() => _WebViewAppState();
}

class _WebViewAppState extends State<WebViewApp> {
  WebViewController controller = WebViewController()
    ..enableZoom(false)

    ..setJavaScriptMode(JavaScriptMode.unrestricted)

    ..addJavaScriptChannel('FileInputChannel', onMessageReceived: (message) async {
      if (message.message == 'pickFile') {
        _pickfile();
      }
    })

    ..loadRequest(
      Uri.parse("https://youtube.com"),
    );

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: WebViewWidget(controller: controller),
      ),
    );
  }
}
oxcyiej7

oxcyiej71#

好了,我自己得到了答案,并在这里分享。
问题是由于控制器在初始化阶段无法再次状态,所以,在初始化它之前只需创建示例(控制器)。*using _controller看起来更清晰

class _WebViewAppState extends State<WebViewApp> {
  late final WebViewController _controller;//initialize here first

  @override
  void initState() {
    _initWebViewController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: WebViewWidget(controller: _controller),
        ),
    );
  }

  Future<void> _pickImage() async {
    final pickedFile =
    await ImagePicker().pickImage(source: ImageSource.camera);
    if (pickedFile != null) {
      final bytes = await pickedFile.readAsBytes();
      final base64 = base64Encode(bytes);
      final jsCode = "receivePhoto('$base64');";
      await _controller.runJavaScript(jsCode);
      print(jsCode);
    }
  }

  void _initWebViewController() {
    _controller = WebViewController()
      ..enableZoom(false)

      ..setJavaScriptMode(JavaScriptMode.unrestricted)

      ..addJavaScriptChannel('FileInputChannel', onMessageReceived: (message) async {
        if (message.message == 'pickFile') {
          _pickImage();
        }
      })

      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
             //progress bar
          },
          onPageStarted: (String url) {
          },
          onPageFinished: (String url) {
          },
          onWebResourceError: (WebResourceError error) {
          },
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      )

      ..loadRequest(
        Uri.parse(url),//url = your initial url
      );
  }
}

相关问题