코드로 우주평화

flutter _ WebView 위젯에서 홈으로 이동, 뒤로가기, 새로고침 본문

나는 이렇게 학습한다/App

flutter _ WebView 위젯에서 홈으로 이동, 뒤로가기, 새로고침

daco2020 2022. 12. 19. 23:22

 

웹뷰를 구현했을 때, 막상 홈버튼이나 뒤로 가기 버튼이 없을 때가 있다. (혹은 위 이미지 처럼 엉뚱한 페이지로 빠지기도 한다)

 

이럴 때는 WebViewController를 이용해 해당 WebView 위젯을 컨트롤할 수 있다.

 

 

 

 

 

WebViewController 사용법

 

해당 HomeScreen 클래스 안에 null이 올 수 있는 controller라는 공용 변수를 선언한다.

class HomeScreen extends StatelessWidget {
  WebViewController? controller;
  ...

 

 

 

 

WebView 위젯 파라미터에 onWebViewCreated를 추가한다 이때 받은 controller을 앞서 생성해두었던 공용 변수 this.controller 에 할당한다.

class HomeScreen extends StatelessWidget {
  WebViewController? controller;

  HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(...),
      body: WebView(
        onWebViewCreated: (WebViewController controller) {  // <--- 이부분
          this.controller = controller;  // <--- 이부분
        },
        initialUrl: 'https://daco2020.tistory.com/';,
        javascriptMode:
            JavascriptMode.unrestricted,
    ),
  );
}

 

 

 

 

이제 controller를 사용하기 위해 AppBar에 아이콘을 추가하고 버튼을 눌렀을 때 controller 메서드를 호출한다.

class HomeScreen extends StatelessWidget {
  WebViewController? controller;

  HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Daco'),
        backgroundColor: Colors.orange, 
        centerTitle: true,
        actions: [  
          IconButton(
            onPressed: () { // <--- 아이콘을 눌렀을 때
              if(controller == null){ // <--- controller 가 null 이면 걍 리턴
                return;
              }
              controller!.goBack(); // <--- controller 가 null 이 아니면 뒤로가기
              // controller!.loadUrl(specificUrl); <--- 이건 특정 Url로 이동
            },
            icon: Icon(
              Icons.home, // <--- 아이콘
            ),
          ),
        ],
      ),
      body: WebView(...),
    );
  }
}

 

goBack 메서드는 뒤로 가기, loadUrl 은 특정 URL로 이동, reload는 새로고침 등등 필요한 메서드를 호출해서 사용할 수 있다.

 

 

 

더 많은 메서드를 알고 싶다면 아래 공식문서를 참고.

 

WebViewController class - webview_flutter library - Dart API

Controls a WebView provided by the host platform. Pass this to a WebViewWidget to display the WebView. Constructors WebViewController() Constructs a WebViewController. WebViewController.fromPlatform(PlatformWebViewController platform) Constructs a WebViewC

pub.dev