7
4

FlutterでJavaScriptと連携する

Last updated at Posted at 2023-10-02

【はじめに】

Flutterを使用したアプリケーションでは、JavaScriptと簡単に連携できます。このチュートリアルでは、flutter_inappwebview パッケージの addJavaScriptHandler メソッドを使用して、JavaScriptからFlutter関数を呼び出す方法を紹介します。

【セットアップ】

まず、flutter_inappwebview パッケージをプロジェクトに追加します。
pubspec.yamlファイルに以下の行を追加してください。

dependencies:
  flutter:
    sdk: flutter
  in_app_webview: ^5.7.2+3 # 最新のバージョンを使用してください

ターミナルを開いてプロジェクト内でflutter pub getでパッケージをインストールして下さい。

【サンプルコード】

以下は、addJavaScriptHandler を使用した簡単な例です。

webViewPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class WebViewPage extends StatelessWidget {
  // JavaScriptから呼び出されるこの関数
  void _receiveMessage(List<dynamic> args) {
    String message = args.first;
    print("Message received from JavaScript: $message");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("WebView Interaction Example"),
      ),
      body: InAppWebView(
        initialFile: 'assets/message.html', // 初期HTMLファイルを設定
        onWebViewCreated: (InAppWebViewController webViewController) {
          // JavaScriptハンドラを追加
          webViewController.addJavaScriptHandler(
            handlerName: 'receiveMessage',
            callback: _receiveMessage,
          );
        },
      ),
    );
  }
}

上記の例では、assets/message.html ファイル内のJavaScriptから receiveMessage ハンドラを呼び出すと、Flutterの _receiveMessage 関数が実行されます。

次に、assets/message.html ファイルで receiveMessage ハンドラを呼び出すJavaScriptの例です:

receiveMessage.html
<!DOCTYPE html>
<html>
<head>
    <title>WebView Interaction Example</title>
</head>
<body>
    <script type="text/javascript">
        function sendMessage() {
            window.flutter_inappwebview.callHandler('receiveMessage', 'Hello from JavaScript!');
        }

        sendMessage();
    </script>
</body>
</html>

このJavaScriptコードは、sendMessage 関数を実行すると、receiveMessage ハンドラが呼び出され、Hello from JavaScript! メッセージがFlutterの _receiveMessage 関数に渡されます。

【最後に】

これで、JavaScriptからDartへデータを送信し、そのデータをDartで処理することができます。
以上が、Flutterのflutter_inappwebviewパッケージのaddJavaScriptHandlerメソッドを使用した基本的な使い方です。これにより、FlutterアプリとWebページとの間で簡単にデータのやり取りが可能となります。

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4