플러터(Flutter)

플러터 4.4.1 웹뷰 webview_flutter

xemaker 2023. 10. 7. 08:53

현재 프로젝트 경로에 Terminal 로 가서

flutter pub add webview_flutter

PS C:\Users\aaa\StudioProjects\first_flutter> flutter pub add webview_flutter

flutter pub add webview_flutter
Resolving dependencies... 
  collection 1.17.2 (1.18.0 available)
  material_color_utilities 0.5.0 (0.8.0 available)
  meta 1.9.1 (1.10.0 available)
+ plugin_platform_interface 2.1.6
  stack_trace 1.11.0 (1.11.1 available)
  stream_channel 2.1.1 (2.1.2 available)
  test_api 0.6.0 (0.6.1 available)
  web 0.1.4-beta (0.2.2-beta available)
+ webview_flutter 4.4.1
+ webview_flutter_android 3.12.0
+ webview_flutter_platform_interface 2.6.0
+ webview_flutter_wkwebview 3.9.1
Changed 5 dependencies!

그럼 이렇게 될것이다.

controller 디렉토리를 만들고 webview_controller.dart 파일을 만든다.

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

class WebviewMainController extends GetxController {
  static WebviewMainController get to => Get.find();

  var 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('http://google.com')) {
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse('http://google.com'));
  WebViewController getController() {
    return controller;
  }
}

main.dart

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

class WebviewMainController extends GetxController {
  static WebviewMainController get to => Get.find();

  var 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('http://google.com')) {
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse('http://google.com'));
  WebViewController getController() {
    return controller;
  }
}

실행하면 된다.

 

android:usesCleartextTraffic="true"

AndroidManifest.xml 에 위를 추가해야 한다. 이전글 참조.