Flutter Webview 4.0 기본 연결 가이드

박한솔·2023년 2월 27일
1

Flutter_webview에 관련된 블로그들의 정보를 보면 Webview가 build 안에 직접적으로 들어있다.

.
.
.
body: Stack(
        children: [
          WebView(
            initialUrl: widget.url,
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _controller = webViewController;
            },
.
.
.

현재 Webview 4.0에서 Webview 사용은 Deprecated되었다!

따라서 WebviewController를 만들어서 WebviewWidget이라는 것에 연결해야 한다.

1. WebviewController 생성

 ** lib/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('https://www.youtube.com/')) {
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse('Your url')); => 웹뷰에 연결할 URL

  WebViewController getController() {
    return controller;
  }
}

2. Webview 연결

** lib/main.dart **

.
.
.
import 'controllers/webview_controller.dart'; => webviewController import

void main() async {

  //전역에 webview controller get 세팅
  Get.put(WebviewMainController());

  //Getx controller는 get find로 가져올 수 있다.
  //controller 안에 'get to => Get.find()'를 사용하면 Get put으로 세팅한 값들을 가져올 수 있다.

  runApp(const MyApp());
}
.
.
.
class _MyHomePageState extends State<MyHomePage> {

//Webview에서 세팅한 WebviewController 불러오기
final controller = WebviewMainController.to
      .getController();
      
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: WillPopScope(
            child: WebViewWidget(controller: controller),
            onWillPop: 뒤로 가기 로직
            ),
       )
}
.
.
.

WebviewController의 유용한 기능

controller.canGoBack() = 웹뷰 페이지가 뒤로 가기 가능 여부(Boolean)
controller.goBack() = 뒤로 가기
controller.loadRequest(Uri.parse( Your url )) = Your url로 이동

이를 활용하면 뒤로 가기나 홈버튼을 만들수 있다.

final controller = WebviewMainController.to
      .getController();

  //home으로 가는 버튼 함수
  void goHome() {
    controller.loadRequest(Uri.parse(Your url));
  }
  
  //앱 나가기 전 dialog
  Future<bool> showExitPopup() async {
    return await showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('Exit App'),
            content: const Text('Do you want to exit an App?'),
            actions: [
              ElevatedButton(
                onPressed: () => Navigator.of(context).pop(false), => false 리턴
                child: const Text('No'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.of(context).pop(true), => true 리턴
                child: const Text('Yes'),
              ),
            ],
          ),
        ) ??
        false;
  }
  
  
  
  
   //뒤로가기 로직(핸드폰 뒤로가기 버튼 클릭시)
  Future<bool> onGoBack() async {
    if (await controller.canGoBack()) { => Webview의 뒤로가기가 가능하면
      controller.goBack(); => Webview 뒤로가기
      return Future.value(false); => onWillPop은 false면 앱을 끄지 않는다.
    } else {
      Future<bool> dialogResult = showExitPopup(); 
      return Future.value(dialogResult); => true이면 앱 끄기;
    }
  }
  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: WillPopScope(
            child: WebViewWidget(controller: controller),
            onWillPop: () => onGoBack()
            ),
       floatingActionButton: Stack(
          children: <Widget>[
          Align(
              alignment: Alignment.bottomRight,
              child: FloatingActionButton(
                onPressed: goHome,
                tooltip: 'goHome',
                child: const Icon(Icons.home_outlined),
              ),
            ),
          ]
       )
}

기존 Webview보다는 더 간단해졌다고 하니 잘 활용하시면 간편한 커스텀 앱을 만드실 수 있을겁니다 :)

profile
치열하게, 하지만 즐겁게

0개의 댓글