AWS Amplify Flutterの最初の観察


Flutter GoogleのUIツールキットを構築するための美しい、ネイティブのモバイル、Web、およびデスクトップのアプリケーションを1つのコードベースからのデスクトップ、および2020年の最速成長モバイルフレームワークの一つです.AWS Amplify recently announced Flutter support 開発者のプレビューでは、それはまだ正式に起動されていないという意味ですが、我々は今それを試し始めることができます.
ここでは、単純な写真共有アプリケーションの認証とストレージ(例Androidでは、行くが、IOSやWebのために動作するはず)を取得から私のログです.

100秒で説明した
  • YouTubehttps://youtu.be/0NgR-Qa5GPE
  • Twitter
  • 埋め込む

  • 新しいフラッターアプリを起動する
    仮定するset up all the prerequisites for Flutter を設定するAndroid Virtual Device and accepting the Android SDK licenses , を使用すると、\->新しいフラッタープロジェクトを起動し、基本的なフラッターアプリケーションのスターターを選ぶことができます.
    新しい増幅フラッタライブラリを追加する必要がありますので、pubspec.yaml and Pub get ダウンロードする
    dependencies:
      flutter:
        sdk: flutter
    
    
      # new
      amplify_core: '<1.0.0'
      amplify_auth_cognito: '<1.0.0'
      amplify_storage_s3: '<1.0.0'
    
      # we happen to also use this in our demo
      file_picker: ^1.13.3
    
      ## this is also available if you want analytics but not covered in this post
      # amplify_analytics_pinpoint: '<1.0.0'
    

    プロジェクトを初期化する
    注意: 2020年8月後半にこれを読んでいるなら、開発者のプレビューにまだあるので、CLIの特別なバージョンが必要になることに注意してください.
    npm i -g @aws-amplify/[email protected]
    
    次に、標準的な増幅セットアップ命令CLI is installed and configured ).
    # command
    amplify init
    
    # prompts
    ? Enter a name for the environment
        `dev`
    ? Choose your default editor:
        `IntelliJ IDEA`
    ? Choose the type of app that you're building: 
        'flutter'
    ⚠️  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/
    ? Do you want to use an AWS profile?
        `Yes`
    ? Please choose the profile you want to use
        `default`
    
    で作成した設定ファイルが表示されます./lib/ 呼ばれるamplifyconfiguration.dart . これは、すべてのパブリック顔の増幅データを保持するインポートできる静的なファイルですが、ほとんどの人々がamplify.configure(amplifyconfig) .
    我々は、認証を必要とする私たちの写真アプリのストレージを設定するつもりです.幸いにもCLIは私たちのために一度に両方を設定します.
    # command
    amplify add storage
    
    # prompts
    ? Please select from one of the below mentioned services:
        `Content (Images, audio, video, etc.)`
    ? You need to add auth (Amazon Cognito) to your project in order to add storage for user files. Do you want to add auth now?
        `Yes`
    ? Do you want to use the default authentication and security configuration?
        `Default configuration`
    ? How do you want users to be able to sign in?
        `Username`
    ? Do you want to configure advanced settings?
        `No, I am done.`
    ? Please provide a friendly name for your resource that will be used to label this category in the project:
        `S3friendlyName`
    ? Please provide bucket name:
        `storagebucketname`
    ? Who should have access:
        `Auth and guest users`
    ? What kind of access do you want for Authenticated users?
        `create/update, read, delete`
    ? What kind of access do you want for Guest users?
        `create/update, read, delete`
    ? Do you want to add a Lambda Trigger for your S3 Bucket?
        `No`
    
    他に何かを設定したら、クラウドにプッシュしてプロビジョニングをオフにすることができます.
    amplify push --y
    
    このプロセスはあなたのためにすべてのリソースを提供するのにしばらくかかるので、それが起こっている間、我々は最初に我々のコードをセットアップすることができます.

    ダイビングコード
    インサイド./lib/main.dart , 必要なものすべてをインポートできます.
    import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
    import 'package:amplify_core/amplify_core.dart';
    import 'package:amplify_storage_s3/amplify_storage_s3.dart';
    import 'amplifyconfiguration.dart';
    // etc
    
    そして、メインページの内部では、設定コードを書くことができます.
    // inside of some class for the page
      Amplify amplify = Amplify();
      bool _isAmplifyConfigured = false;
    
      @override
      initState() {
        super.initState();
        _initAmplifyFlutter();
      }
    
      void _initAmplifyFlutter() async {
        AmplifyAuthCognito auth = AmplifyAuthCognito();
        AmplifyStorageS3 storage = AmplifyStorageS3();
        amplify.addPlugin(
            authPlugins: [auth],
            storagePlugins: [storage],
        );
        await amplify.configure(amplifyconfig);
    
        setState(() {
          _isAmplifyConfigured = true;
        });
      }
    
    このように我々は少し負荷画面を追加することができます_isAmplifyConfigured 我々が望むならば.
    アプリの残りの部分については、フラッターUI体験を自分で書く必要がありますが、ハード部分は、増幅コードを書くからです.

    ウィジェットでのAmplify Authの使用
    適切な関数を呼び出します(docs here ) 必要に応じて.以下にユーザに署名する方法を示します.
    import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
    import 'package:amplify_core/amplify_core.dart';
    import 'package:flutter/material.dart';
    
    class SignInView extends StatefulWidget {
      @override
      _SignInViewState createState() => _SignInViewState();
    }
    
    class _SignInViewState extends State<SignInView> {
      final usernameController = TextEditingController();
      final passwordController = TextEditingController();
    
      String _signUpError = "";
      List<String> _signUpExceptions = [];
    
      @override
      void initState() {
        super.initState();
      }
    
      void _signIn() async {
        // Sign out before in case a user is already signed in
        // If a user is already signed in - Amplify.Auth.signIn will throw an exception
        try {
          await Amplify.Auth.signOut();
        } on AuthError catch (e) {
          print(e);
        }
    
        try {
          SignInResult res = await Amplify.Auth.signIn(
              username: usernameController.text.trim(),
              password: passwordController.text.trim());
          Navigator.pop(context, true);
        } on AuthError catch (e) {
          setState(() {
            _signUpError = e.cause;
            _signUpExceptions.clear();
            e.exceptionList.forEach((el) {
              _signUpExceptions.add(el.exception);
            });
          });
        }
      }
    
    // etc for the Widget build
    

    ウィジェットでの増幅ストレージの使用
    適切な関数を呼び出します(docs here ) 必要に応じて.新しい写真をアップロードする方法を以下に示します.
    import 'package:flutter/material.dart';
    import 'dart:io';
    import 'package:file_picker/file_picker.dart';
    import 'package:amplify_core/amplify_core.dart';
    import 'package:amplify_storage_s3/amplify_storage_s3.dart';
    
    class ImageUploader extends StatelessWidget {
      void _upload(BuildContext context) async {
        try {
          print('In upload');
          // Uploading the file with options
          File local = await FilePicker.getFile(type: FileType.image);
          local.existsSync();
          final key = new DateTime.now().toString();
          Map<String, String> metadata = <String, String>{};
          metadata['name'] = 'filename';
          metadata['desc'] = 'A test file';
          S3UploadFileOptions options = S3UploadFileOptions(
              accessLevel: StorageAccessLevel.guest, metadata: metadata);
          UploadFileResult result = await Amplify.Storage.uploadFile(
              key: key, local: local, options: options);
    
          print('File uploaded.  Key: ' + result.key);
          Navigator.pop(context, result.key);
        } catch (e) {
          print('UploadFile Err: ' + e.toString());
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(children: [
          RaisedButton(
            child: Text("Upload Image"),
            onPressed: () {
              _upload(context);
            },
          )
        ]);
      }
    }
    

    フルデモアプリ
    あなたはすべてのこのセットアップでは、デモのアプリを参照したい場合は、頭にamplify-flutter 例:https://github.com/aws-amplify/amplify-flutter/tree/master/example
    (そして、⭐ - それは本当に役立つ!)

    次は何ですか.
    新しいSDKであると、フラッタ開発者プレビューは間違いなくJS/Android/IOS SDKと機能パリティを欠いています.ここ数ヶ月で何が来るかは以下の通りです:
  • API(REST/Graphql):APIカテゴリはAWS AppSyncまたはREST APIとAmazon APIゲートウェイとAWSラムダを使用してハンドラーによってバックアップされたGraphSQLを使用してデータを取得し、持続するためのインターフェイスを提供します.
  • Datastore :データストアは、オフラインでオンラインのシナリオの追加コードを書くことなく、共有データと分散データをレバレッジするためのプログラミングモデルを提供します.
  • 予測:予測カテゴリは、テキストを翻訳、テキストを音声に変換するなどのフロントエンド上のAI/ML使用ケースを可能にし、画像、テキスト、ラベル、顔を認識する.
  • Auth:ウェブのUIで社会的なサインでAuthカテゴリを拡張します
  • ストレージ:我々は能力アップロードを追跡し、進行状況をダウンロードしてストレージカテゴリを拡張します
  • エスケープハッチ:我々は、開発者がより簡単に低レベルの生成IOSとAndroidのAWSモバイルSDKを追加ユースケースのために使用できるように、'エスケープハッチ'のサポートを追加します.