⭐️ 개발/플러터

[프로젝트] 블로그 웹앱 (1) Controller 사용

짱구러버 2022. 11. 2. 03:53
728x90

들어가기 앞서...

컨트롤러란 위젯들을 프로그램 적으로 조정 할수 있는 것제공해주는 을 말한다. 

잎으로 나오는 위젯들을 이제 컨트롤러로 조정할 수 있게 될것이다.

 

 

주의 깊게 봐야하는 점...

 

간단한 설명으로는...

 


본문으로...

  • Controller 를 사용 해보자! 

웹뷰가 생성이 될 때 전달 되는 것을 WebViewController를 사용해 제어 가능하다.

웹뷰가 생성되면 onWebViewCreated 콜백 함수가 실행이 된다.

 

 

쉽게 생각하려면, on 이라고 적혀있는것은 '~ 할때' 라고 생각하면 쉽다.

onWebViewCreated -> 웹뷰가 생성될떄! 

on 이라는 것은 무엇을 할때라는 뜻이다!

웹뷰가 생성되었을때! 라는 뜻이다.

만약에 함수에 대한 정의 및 사용법을 알기 위해서는 option + B 단축키를 눌러보자

 

WebViewCreatedCallback 함수 정의

webView Controller 를 파라미터로 제공하는 것을 볼 수 있다!

  • 이제 코드에 적용 해보자!
class HomeScreen extends StatelessWidget {
  WebViewController? controller;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text('hi my blog'),
        centerTitle: true,       
      ),
      body: WebView(
        onWebViewCreated: (WebViewController controller){
          this.controller = controller;
        },
        initialUrl: homeUrl,
        javascriptMode: JavascriptMode.unrestricted,
      ),
    );
  }
}

컨트롤러를 어딘가에 저장해놓으면은 저장한 컨트롤러를 빼와서 사용하게끔, 해야 사용을 할수 있다.

그 역할을 웹 뷰컨트롤러를 null 이 가능하게끔 선언을 해준다.

위에 선언해둔 controller 를 넣어준다.

 

그렇게 되면 웹뷰가 생성되고나서 controller를 상단에 선언해둔 WebViewController? controller 에 저장해서 밑에 선언이 가능해졌다!

 

  • 웹뷰 오른쪽 상단에 홈 버튼을 만들거다!

앱바의 오른쪽 위치에 넣을것인데 정해진 명칭이 있다!

action 안에 원하는 것들을 넣어줄 수 있다.

IconButton 은 아이콘을 버튼으로 만들어 주는 위젯이다.

onPressed 는 버튼을 눌렀을떄 우리가 실행할 함수

icon은 보여줄 아이콘을 넣어주면 된다.

Icon() 은 플러터에서 기본으로 제공해주는 위젯이므로 아이콘을 home 으로 적용해보자!

class HomeScreen extends StatelessWidget {
  WebViewController? controller;

  final homeUrl = 'https://hitang.tistory.com/';
  HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text('hi my blog'),
        centerTitle: true,
        actions: [
          IconButton(onPressed: (){
            if(controller == null) {
              return;
            }
            controller!.loadUrl(homeUrl);
          }, icon: Icon(
            Icons.home,
          ))
        ],
      ),
      body: WebView(
        onWebViewCreated: (WebViewController controller){
          this.controller = controller;
        },
        initialUrl: homeUrl,
        javascriptMode: JavascriptMode.unrestricted,
      ),
    );
  }
}

 

 

상단에 공통적으로 사용할 url 을 final 함수로 선언을 해두고, actions 리스트 안에 아이콘 버튼을 의미하는 IconButton() 을 사용해준다.

 

...
final homeUrl = '이동할 주소';
...
action: [
	IconButton(onPressed: onPressed, icon: icon)
    // opPressed: print('눌렀을떄 클릭 이벤트를 넣어주면 된다. ')
    // 우리가 웹뷰가 생성될떄 controller 를 사용해서 조정을 할 것이다.
	// controller 가 null 이면 IconButton을 눌러도 이벤트 함수가 일어나지 않게 한다.
    if(controller == null){    
    	return;
    }
    // controller 가있으면 loadUrl() 로 경로 이동!
    controller!.loadUrl(homeUrl);
	// 플러터 내부에서 제공해주는 아이콘 중 홈을 사용한다.
	// icon: Icon(Icon.home);
],
) 
body: WebView(
	onWebViewCreated: (WebViewController controller){},
)
...

ios 오른쪽 상단 홈 버튼

 


끝으로...

  1. Controller 의 정의와 사용법을 알게 되었다.
  2. 웹뷰가 생성될 시점에 컨트롤러를 통제 할 수 있다.
  3. 플러터가 제공하는 Icon 을 사용해 홈버튼을 만들고 액션까지 할 수 있다.

 

728x90