概要
今回のブログポストではwebview_flutter
パッケージを使ってアプリ内でウェブページを表示する方法について説明します。
- webview_flutter: https://pub.dev/packages/webview_flutter
このブログポストで紹介するソースコードは下記のリンクで確認できます。
Flutterプロジェクト生成
Flutterでwebview_flutterの使い方を確認するため下記のコマンドを使ってFlutterの新しいプロジェクトを生成します。
flutter create webview_flutter_example
webview_flutterのインストール
webview_flutter
を使うために、次のコマンドを実行してwebview_flutter
パッケージをインストールします。
flutter pub add webview_flutter
このようにインストールしたwebview_flutterを使う方法について説明します。
Androidの設定
アンドロイドではwebview_flutter
を使うためminSdkVersion
を19
で設定する必要があります。./android/app/build.gradle
ファイルを開いて下記のように修正します。
android {
defaultConfig {
minSdkVersion 19
}
}
使い方
webview_flutter
の使い方を確認するため./lib/main.dart
ファイルを開いて下記のように修正します。
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
...
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const WebView(
initialUrl: 'https://deku.posstree.com/en/',
javascriptMode: JavascriptMode.unrestricted,
);
}
}
このコードを実行してみると次のような画面が表示されることが確認できます。

SafeArea
例題コードを実行してみると、上のステータスバーと下のホームバーの下にウェブページが表示されることが確認できます。SafeArea
ウィジェットを使うとウェブページをステータスバーとホームバーと重ねないように表示することができます。また、./lib/main.dart
ファイルを開いて下記のように修正します。
...
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Scaffold(
body: SafeArea(
child: WebView(
initialUrl: 'https://deku.posstree.com/en/',
javascriptMode: JavascriptMode.unrestricted,
),
),
);
}
}
これを実行すると次のようにウェブページがうまく表示されることが確認できます。

gestureNavigationEnabled
アプリやウェブで以前のページに戻るため、スワイプを使います。このような機能を有効にするためgestureNavigationEnabled
オプションを使う必要があります。また、./lib/main.dart
ファイルを開いて下記のように修正します。
...
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Scaffold(
body: SafeArea(
child: WebView(
initialUrl: 'https://deku.posstree.com/en/',
javascriptMode: JavascriptMode.unrestricted,
gestureNavigationEnabled: true,
),
),
);
}
}
また、アプリを再実行して、次のページに移動した後、スワイプをすると次のように以前のページに戻れることができます。

userAgent
ウェブページでグーグルログインを使う場合、次のように403: disallowed_useragent
エラーが発生します。

これを解決するためにはWebView
にuserAgent
を設定する必要があります。./lib/main.dart
ファイルを開いて下記のように修正します。
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Scaffold(
body: SafeArea(
child: WebView(
initialUrl: 'https://deku.posstree.com/en/',
javascriptMode: JavascriptMode.unrestricted,
gestureNavigationEnabled: true,
userAgent: "random",
),
),
);
}
}
またアプリを再実行してグーグルログインを実行すると、次のようにグーグルのログイン画面がうまく表示されることが確認できます。

完了
これでFlutterでwebview_flutter
を使ってアプリ内でウェブページを表示する方法についてみてみました。また、webview_flutter
を使ったら発生する問題を解決する方法も確認しました。
私のブログが役に立ちましたか?下にコメントを残してください。それは私にとって大きな大きな力になります!
アプリ広報
Deku
が開発したアプリを使ってみてください。Deku
が開発したアプリはFlutterで開発されています。興味がある方はアプリをダウンロードしてアプリを使ってくれると本当に助かります。