Flutter×Amplifyの環境構築(2021年7月現在最新版)

<h1>環境</h1>
Flutter 2.2.3
nodejs v12.14.0
AWSアカウント開設済
Flutter PJを作成済

<h1>概要</h1>
AWS公式のflutterチュートリアルに基本沿って今回の環境構築を行っています。
https://aws.amazon.com/jp/getting-started/hands-on/build-flutter-app-amplify/module-two/
2021年7月の現時点で変わっている部分(本記事の手順②のpubspec.yaml設定以降)がわずかながらあったので最初から記事に残してみました。


<h1>手順①Amplifyをインストール&初期化する</h1>
AmplifyのCLIとAmplify-Flutter デベロッパープレビューバージョンをダウンロードします。

```
npm install -g @aws-amplify/cli@flutter-preview
```
<hr>
amplifyの設定をします。

```
amplify configure
```
<hr>
任意のregionとusernameを選択します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/0f8c194b-f238-ad2f-dbe2-e71ce33e0db9.png)
<hr>
AWSのIAMユーザーが自動的に開くのでステップ5までデフォルトで進み、アクセスキーとシークレットキーを取得します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/9f61f8a6-bc46-df9b-cff4-2679aa0d43bc.png)
<hr>
ターミナルに戻り、取得したキーをコピペし、Profile Nameを設定します(今回はデフォルトのまま)。

```
Enter the access key of the newly created user:
? accessKeyId:  ********************
? secretAccessKey:  ****************************************
This would update/create the AWS Profile in your local machine
? Profile Name:  default
```
<hr>
Amplify プロジェクトを初期化します。

```
amplify init
```
<hr>
初期化の設定は基本的にデフォルトで進めます。今回私はAndroid studioをvs codeの代わりに使うのでそこだけ変更しました。

```
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project awsfluttertutorial
The following configuration will be applied:

Project information
| Name: awsfluttertutorial
| Environment: dev
| Default editor: Visual Studio Code
| App type: flutter
| Configuration file location: ./lib/

? Initialize the project with the above configuration? No
? Enter a name for the environment dev
? Choose your default editor: Android Studio
? Choose the type of app that you're building flutter
Please tell us about your project
? Where do you want to store your configuration file? ./lib/
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS profile

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

? Please choose the profile you want to use default
Adding backend environment dev to AWS Amplify Console app: d1yo7v88ujb4p7
\ Initializing project in the cloud...

CREATE_IN_PROGRESS amplify-awsfluttertutorial-dev-162814 AWS::CloudFormation::Stack Thu Jul 22 2021 16:28:17 GMT+0900 (GMT+09:00) User Initiated
CREATE_IN_PROGRESS DeploymentBucket                      AWS::S3::Bucket            Thu Jul 22 2021 16:28:22 GMT+0900 (GMT+09:00)
CREATE_IN_PROGRESS AuthRole                              AWS::IAM::Role             Thu Jul 22 2021 16:28:22 GMT+0900 (GMT+09:00)
CREATE_IN_PROGRESS UnauthRole                            AWS::IAM::Role             Thu Jul 22 2021 16:28:22 GMT+0900 (GMT+09:00)
\ Initializing project in the cloud...

CREATE_IN_PROGRESS AuthRole         AWS::IAM::Role  Thu Jul 22 2021 16:28:23 GMT+0900 (GMT+09:00) Resource creation Initiated
CREATE_IN_PROGRESS UnauthRole       AWS::IAM::Role  Thu Jul 22 2021 16:28:23 GMT+0900 (GMT+09:00) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket AWS::S3::Bucket Thu Jul 22 2021 16:28:24 GMT+0900 (GMT+09:00) Resource creation Initiated
- Initializing project in the cloud...

CREATE_COMPLETE AuthRole                              AWS::IAM::Role             Thu Jul 22 2021 16:28:43 GMT+0900 (GMT+09:00)
CREATE_COMPLETE UnauthRole                            AWS::IAM::Role             Thu Jul 22 2021 16:28:43 GMT+0900 (GMT+09:00)
CREATE_COMPLETE DeploymentBucket                      AWS::S3::Bucket            Thu Jul 22 2021 16:28:46 GMT+0900 (GMT+09:00)
CREATE_COMPLETE amplify-awsfluttertutorial-dev-162814 AWS::CloudFormation::Stack Thu Jul 22 2021 16:28:48 GMT+0900 (GMT+09:00)
√ Successfully created initial AWS cloud resources for deployments.
√ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add <category>" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

```

<h1>手順②FlutterにAmplifyを導入する</h1>
pubspec.yamlに注入しflutter pub getを実行します。AWSの公式チュートリアルではamplify_coreを記述するようになっていますが、2021年7月現在ではamplify_flutterでないと後述のインスタンスを生成できないようになっています。

```pubspec.yaml
amplify_flutter: '<1.0.0'
```

```
flutter pub get
```
<hr>
Stateクラス内でamplifyのインスタンスを生成します。(例えばFlutterの新規PJの場合はmain.dartの_MyAppState直下になります)

```
final _amplify = Amplify;
```
<hr>
amplify導入できているかテストする関数を作成します。

```
void _configureAmplify() async {
  try {
    await _amplify.configure(amplifyconfig);
    print('Successfully configured Amplify 🎉');
  } catch (e) {
    print('Could not configure Amplify ☠️');
  }
}
```
<hr>
initState関数をオーバーライドし、先ほどの確認用関数をアプリ起動時に呼ぶようにします。

```
@override
  void initState() {
    super.initState();
    _configureAmplify();
    _authService.showLogin();
  }
```
<hr>
アプリを実行すると、コンソールにFlutterPJにamplifyの導入が成功している旨が表示されます。

```
Successfully configured Amplify 🎉
```