[flutter] 플러터 Riverpod와 웹뷰 연동 방법

플러터는 UI 개발을 위한 크로스 플랫폼 프레임워크로, 다양한 기능과 라이브러리를 제공합니다. Riverpod는 플러터의 상태 관리를 도와주는 라이브러리로, 효율적이고 간편한 상태 관리를 위해 사용됩니다. 이번 글에서는 Riverpod와 웹뷰를 연동하는 방법에 대해 알아보겠습니다.

1. 웹뷰 패키지 설치

플러터 프로젝트에 웹뷰를 사용하기 위해서는 먼저 flutter_webview_plugin 패키지를 설치해야 합니다. pubspec.yaml 파일에 다음과 같이 패키지를 추가합니다:

dependencies:
  flutter_webview_plugin: ^0.4.0

설치 후 flutter packages get 명령어를 실행하여 패키지를 내려받습니다.

2. 상태 관리 설정

flutter_riverpod를 사용하기 위해 pubspec.yaml 파일에 다음 패키지를 추가합니다:

dependencies:
  riverpod: ^0.14.0

설치 후 flutter packages get 명령어를 실행하여 패키지를 내려받습니다.

3. 웹뷰 위젯 생성

이제 웹뷰 위젯을 생성하고 flutter_riverpod를 통해 상태를 관리하는 방법에 대해 알아보겠습니다.

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:riverpod/riverpod.dart';

final webViewUrlProvider = StateProvider<String>((ref) => '');

class WebviewScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('웹뷰 연동'),
      ),
      body: Consumer(builder: (context, watch, _) {
        final webViewUrl = watch(webViewUrlProvider).state;
        return WebviewScaffold(
          url: webViewUrl,
          withJavascript: true,
          withZoom: true,
          appBar: AppBar(
            title: Text('웹뷰'),
          ),
        );
      }),
    );
  }
}

위 예시 코드는 flutter_webview_plugin을 사용하여 웹뷰를 생성하고, flutter_riverpodStateProvider로 웹뷰의 URL을 관리하는 방법을 보여줍니다. StateProviderwatch 메서드를 통해 상태를 가져오고 변경사항을 감지할 수 있습니다. 이를 활용하여 웹뷰의 URL을 동적으로 변경하거나 상태에 따라 다른 웹페이지를 보여줄 수 있습니다.

4. 상태 변경

flutter_riverpod를 통해 상태를 변경하는 방법을 알아보겠습니다.

final webViewUrlProvider = StateProvider<String>((ref) => '');

class WebviewScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('웹뷰 연동'),
      ),
      body: Consumer(builder: (context, watch, _) {
        final webViewUrl = watch(webViewUrlProvider).state;
        return Column(
          children: [
            ElevatedButton(
              onPressed: () {
                // 상태 변경
                context.read(webViewUrlProvider).state = 'https://www.google.com';
              },
              child: Text('Google 열기'),
            ),
            WebviewScaffold(
              url: webViewUrl,
              withJavascript: true,
              withZoom: true,
              appBar: AppBar(
                title: Text('웹뷰'),
              ),
            ),
          ],
        );
      }),
    );
  }
}

위 예시 코드는 ElevatedButton 위젯을 통해 버튼을 생성하고, 버튼을 누를 때마다 webViewUrlProvider의 상태를 변경하여 웹뷰의 URL을 동적으로 변경하는 방법을 보여줍니다.

이제 플러터 앱에서 웹뷰를 연동하는 방법에 대해 알 수 있었습니다. flutter_webview_plugin을 통해 웹뷰를 사용하고, flutter_riverpod를 통해 상태를 효율적으로 관리할 수 있습니다.

참고 자료

위의 자료를 참고하여 더 자세한 내용을 학습하실 수 있습니다.