Open4

【Flutter】環境構築 & WebViewを表示するアプリを作ってみる

だーら(Flamers / Memotia)だーら(Flamers / Memotia)

インストール

% Running `brew update --auto-update`...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core and homebrew/cask).
==> New Formulae
(略)

==> Downloading https://storage.googleapis.com/flutter_infra_release/releases/stable/macos/flutter_macos_arm64_3.13.2-stable.zip
############################################################################################################################# 100.0%
==> Installing Cask flutter
==> Linking Binary 'dart' to '/opt/homebrew/bin/dart'
==> Linking Binary 'flutter' to '/opt/homebrew/bin/flutter'
🍺  flutter was successfully installed!
  • インストール完了確認
% flutter --version
Flutter 3.13.2 • channel stable • https://github.com/flutter/flutter.git
...
  • Apple SiliconのMacなので、Rosettaをアップデートする必要があるとのこと
% sudo softwareupdate --install-rosetta --agree-to-license
  • flutter doctorで確認
% flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.13.2, on macOS 13.2.1 22D68 darwin-arm64, locale ja-JP)
[!] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[!] Xcode - develop for iOS and macOS (Xcode 14.3)
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart
        side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] VS Code (version 1.81.1)
[✓] Connected device (2 available)
[✓] Network resources

! Doctor found issues in 2 categories.
  • cocoapodsをHomebrewでインストール公式doc
% brew install cocoapods
  • Android SDK Command-line Tools(latest)をAndroid StudioでGUIでインストール
  • Androidのライセンスに同意
flutter doctor --android-licenses
  • 準備OK!
% flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.13.2, on macOS 13.2.1 22D68 darwin-arm64, locale ja-JP)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] VS Code (version 1.81.1)
[✓] Connected device (2 available)
[✓] Network resources

• No issues found!
だーら(Flamers / Memotia)だーら(Flamers / Memotia)

アプリを起動してみる

  • こちらの本に従う
  • VSCodeから新規のflutterプロジェクトを作成し、Start Debuggingする
    • warningが出ているのであとで解消したい
  • Chrome / Macアプリ / Androidシミュレーター / iOSエミュレーターで確認可能
だーら(Flamers / Memotia)だーら(Flamers / Memotia)

WebViewを表示するアプリを作ってみる

  • iOS/Androidのシミュレータで、WebViewを表示する
  • ブラウザバック機能がほしいので「戻る」ボタンを設置する
  • webview_flutterというpackageを利用
  • iOSのInfo.plistや、AndroidのAndroidManifest.xmlは編集していない。
  • macOSアプリでの起動はできていない
  • ソースコード
    • (Flutter初心者なのでコードの正確性はご容赦を...)
main.dart
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late WebViewController _controller;

  
  void initState() {
    super.initState();

    _controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setBackgroundColor(const Color(0x00000000))
    ..setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          // Update loading bar.
        },
        onPageStarted: (String url) {},
        onPageFinished: (String url) {},
        onWebResourceError: (WebResourceError error) {},
        onNavigationRequest: (NavigationRequest request) {
          if (request.url.startsWith('https://www.youtube.com/')) {
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse('https://app.memoria-vr.com/user/mypage'));
  }

  
  Widget build(BuildContext context)
  {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter Simple WebView", style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.blue,
      ),
      body: WebViewWidget(controller: _controller),
      floatingActionButton: FloatingActionButton(
        onPressed: _controller.goBack,
        child: const Icon(Icons.arrow_back),
      ),
    );
  }
}

トラブルシューティング

  • Androidのシミュレーターにて、ERR_NAME_NOT_RESOLVEDと表示される
  • そもそもシミュレーター自体がインターネットに繋がっていないことが判明(シミュレーター内のchromeアプリでwebページも表示できない)
  • こちらの記事に従って、シミュレーターのネットワークの設定を変更する
  • シミュレーターを再起動して、ただしく表示された。

補足

  • macOSアプリでは起動しなかった
_AssertionError ('package:webview_flutter_platform_interface/src/platform_webview_controller.dart': Failed assertion: line 26 pos 7: 'WebViewPlatform.instance != null': A platform implementation for `webview_flutter` has not been set. Please ensure that an implementation of `WebViewPlatform` has been set to `WebViewPlatform.instance` before use. For unit testing, `WebViewPlatform.instance` can be set with your own test implementation.)
  • あとで時間あったら調べる