AWS Amplify가 Flutter를 지원하게 되어서 한번 해봤습니다

AWS Amplify가 Flutter도 지원하는 것 같아서 한번 시도 해 보았습니다!
2020.10.05

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

2020년 8월 20일 AWS Amplify가 Flutter를 개발자 평가판으로 지원하게 되었습니다.

개발자 평가판이라 몇 가지 서비스들만 지원되고 있습니다.

Amazon Cognito, Amazon pinpoint, Amazon S3를 지원하고 있고 amplify-flutter GitHub의 Readme에도 아직 프로덕션 레벨로는 추천하고 있지 않네요.

Amplify for Flutter is in preview, and is not recommended for production use at this time. During this phase, we are iterating on the code base, and looking for your feedback and collaboration. WE'D LOVE TO GET YOUR FEEDBACK! :-)..

이번 블로그는 아래의 공식 튜토리얼 문서를 진행 해보겠습니다. 튜토리얼의 내용은 간단하고, 이런 느낌으로 진행되는구나 정도로 보시면 좋을 것 같습니다.

프로젝트 셋업

이 튜토리얼은 아래의 조건으로 진행합니다.

  • Flutter 1.20.0 버전 이상
  • Android Studio (저는 Visual Studio Code로 진행했습니다.)
  • Amplify-Flutter Developer Preview version
    • npm install -g @aws-amplify/cli@flutter-preview
  • 사용 가능한 AWS 계정

어플리케이션 셋업

flutter create todo로 사용할 디렉토리에서 프로젝트를 만들어주세요.

프로젝트 폴더 내에 있는 pubspec.yaml에 Amplify를 추가 해보겠습니다.

dependencies:
  flutter:
    sdk: flutter

  amplify_core: '<1.0.0'
  amplify_auth_cognito: '<1.0.0'
  amplify_analytics_pinpoint: '<1.0.0'

sdk: flutter 밑에 위와 같이 3줄을 추가해주세요.

파일을 변경한 후 flutter pub get으로 패키지를 설치하면 준비 끝입니다.

iOS 11.0 이상의 버전을 사용하는 경우 ios/podfile 에서

# Uncomment this line to define a global platform for your project
platform :ios, '11.0'

와 같이 변경해주세요.

앱 작성

import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:flutter/material.dart';
import 'package:amplify_core/amplify_core.dart';
import 'package:amplify_analytics_pinpoint/amplify_analytics_pinpoint.dart';
import 'amplifyconfiguration.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _amplifyConfigured = false;

  // Instantiate Amplify
  Amplify amplifyInstance = Amplify();

  @override
  void initState() {
    super.initState();
    _configureAmplify();
  }

  void _configureAmplify() async {
    if (!mounted) return;

    // Add Pinpoint and Cognito Plugins
    AmplifyAnalyticsPinpoint analyticsPlugin = AmplifyAnalyticsPinpoint();
    AmplifyAuthCognito authPlugin = AmplifyAuthCognito();
    amplifyInstance.addPlugin(authPlugins: [authPlugin]);
    amplifyInstance.addPlugin(analyticsPlugins: [analyticsPlugin]);

    // Once Plugins are added, configure Amplify
    await amplifyInstance.configure(amplifyconfig);
    try {
      setState(() {
        _amplifyConfigured = true;
      });
    } catch (e) {
      print(e);
    }
  }

  void _recordEvent() async {
    AnalyticsEvent event = AnalyticsEvent("test");
    event.properties.addBoolProperty("boolKey", true);
    event.properties.addDoubleProperty("doubleKey", 10.0);
    event.properties.addIntProperty("intKey", 10);
    event.properties.addStringProperty("stringKey", "stringValue");
    Amplify.Analytics.recordEvent(event: event);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Amplify Core example app'),
            ),
            body: ListView(padding: EdgeInsets.all(10.0), children: <Widget>[
              Center(
                child: Column(children: [
                  const Padding(padding: EdgeInsets.all(5.0)),
                  Text(_amplifyConfigured ? "configured" : "not configured"),
                  RaisedButton(
                      onPressed: _amplifyConfigured ? _recordEvent : null,
                      child: const Text('record event'))
                ]),
              )
            ])));
  }
}

_configureAmplify()는 플러터 라이브러리를 초기화하기 위한 함수입니다. 플러터 앱의 루트 레벨에서 한번 실행시켜야 합니다.

_recordEvent()는 이벤트를 기록하여 Amazon Pinpoint로 전송하는 함수입니다.

import 'amplifyconfiguration.dart'; 이 부분에 에러가 뜨게 될텐데요, 아직 프로젝트에 Amplify를 초기화 하지 않아서 그런거기 때문에 계속해서 진행해 보겠습니다.

AWS와 연결

amplify --version으로 Amplify의 버전에 -flutter-preview가 붙어 있는지 확인해주세요.

만약 없다면 npm install -g @aws-amplify/cli@flutter-preview를 실행해주세요.

다음 amplify init으로 Amplify를 초기화 시켜 봅시다.

 amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project todo
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building flutter
Please tell us about your project
⚠️  Flutter project support in the Amplify CLI is in DEVELOPER PREVIEW.
Only the following categories are supported:
 * Auth
 * Analytics
 * Storage
? Where do you want to store your configuration file? ./lib/
Using default provider  awscloudformation

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use flutter-todo

기본적으로 default 세팅으로 진행해주셔도 문제 없습니다.

Amplify profile은 터미널에서 amplify configure로 만드시면 됩니다.

이제 서비스들을 붙여봅시다.

amplify add analytics를 터미널에서 실행 해주세요.

 amplify add analytics
? Select an Analytics provider Amazon Pinpoint
? Provide your pinpoint resource name: todo
Adding analytics would add the Auth category to the project if not already added.
? Apps need authorization to send analytics events. Do you want to allow guests and unauthenticated users to send analytics events? (we recommend you allow this when getting started) Yes
Successfully added auth resource locally.
Successfully added resource todo locally

위와 같이 성공 했다는 메시지가 나오면 안심입니다. ?

현재 로컬에만 추가가 되었기 때문에 aws 계정에도 추가 해봅시다.

amplify push를 하게 되면 로컬에 추가된 서비스들이 aws 계정에서 활성화 되게 됩니다.

위 과정이 끝나면 아까 필요했던 부분인 amplifyconfiguration.dart 파일이 생성 되는데요. 이 파일은 AWS 백엔드 리소스와 연결할 때 사용하는 민감한 정보들을 포함하기 때문에 누출되거나 잃어버리게 되면 재생성 해주셔야 합니다.

amplify push가 완료되면 이제 실행해보겠습니다.

버튼을 누르고 Amazon Pinpoint 대쉬보드로 가서 확인을 해보면

이벤트가 잘 기록되는 걸 확인할 수 있습니다.

감상평

아직까지는 개발자 평가판이라 사용할 수 있는 기능이 많지는 않습니다. 어느정도 서비스들을 연결하여 사용할 수 있을 때까지는 조금 더 기다려야 할 것 같네요. 앞으로 빠른 시일내에 더 많은 기능을 지원하여 유용하게 사용할 수 있게 되기를 기원해 봅니다. ?