3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Flutter] ローカルHTMLをWebViewで描画してみた

Last updated at Posted at 2023-11-16

はじめに

この記事では、ローカルHTMLファイルの読み込みやwebview_flutter 4.4.2を使ったWebViewの表示、JavaScriptとDartの連携に関する方法を記載します。記事が読者のお役に立てれば幸いです!

サンプルコード

test_page.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

class TestPage extends StatefulWidget {
  const TestPage({Key? key}) : super(key: key);

  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  late WebViewController controller;
  late Future<void> controllerInitialization;
  @override
  void initState() {
    super.initState();
    controllerInitialization = initController();
  }

  Future<void> initController() async {
    final html = await rootBundle.loadString('asset/index.html');
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(onPageStarted: (String url) {
        // ページが読み込まれたときにJavaScriptからDartに変数を渡す
        getJavaScriptVariable();
      }))
      ..loadRequest(
        Uri.dataFromString(
          html,
          mimeType: "text/html",
          encoding: Encoding.getByName("utf-8"),
        ),
      );
  }

  Future<void> getJavaScriptVariable() async {
    // JavaScriptの変数を取得
    print("----------------------------------");
    final test = await controller.runJavaScriptReturningResult("sendMs();");
    print(test);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<void>(
      future: controllerInitialization,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // 初期化が完了したらWebViewを表示
          return Scaffold(
            appBar: AppBar(title: Text("WebView")),
            body: WebViewWidget(controller: controller),
          );
        } else {
          // 初期化中はローディングなどを表示
          return const CircularProgressIndicator();
        }
      },
    );
  }
}
asset/index.html

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <title>js_to_dart</title>
</head>

<body>
  <h1>hello world</h1>

  <script>
    let testNum = 10;
    function sendMs() {
      return testNum;
    }
  </script>
</body>

</html>

pubspec.yaml
  assets:
    - asset/index.html

実行例

jstodart.png
jstodart2.png

index.htmlを変更することでGoogle Mapも読み込むことができました。
jstodart3.png

おまけ

指定したURLをWebViewで描画する方法
loadRequestの部分を

..loadRequest(Uri.parse("URL"));

にするだけです。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?