AWS Amplify Flutter(开发者预览版)抢先看
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
Flutter是谷歌的 UI 工具包,用于从单一代码库构建美观的、原生编译的移动、Web 和桌面应用程序,也是 2020 年增长最快的移动框架之一。AWS Amplify 最近宣布在开发者预览版中支持 Flutter,这意味着它尚未正式发布,但我们现在就可以开始试用了。
这是我创建一个简单的照片共享应用程序的日志,该应用程序具有身份验证和存储功能(示例在 Android 上,但也应该适用于 iOS 和 Web)。
100秒讲解
- YouTube:https://youtu.be/0NgR-Qa5GPE
- 推特:https ://twitter.com/swyx/status/1298349861696282625?s=20
- Dev.to 嵌入:
创建一个新的 Flutter 应用
假设您已经设置了 Flutter 的所有先决条件(包括设置Android 虚拟设备和接受 Android SDK 许可),您可以前往“文件”->“新建”->“新建 Flutter 项目”,然后选择基本的 Flutter 应用程序启动器。
我们需要添加新的 Amplify Flutter 库,所以请务必添加pubspec.yaml并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'
初始化 Amplify 项目
注意:如果您在 2020 年 8 月下旬阅读本文,请注意,您需要一个特殊版本的 CLI,因为它仍处于开发者预览阶段:
npm i -g @aws-amplify/cli@4.26.1-flutter-preview.0
然后我们按照标准的 Amplify 设置说明进行操作(假设CLI 已安装和配置)。
# 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/请注意,您会看到一个名为`.config` 的配置文件amplifyconfiguration.dart。这是一个静态文件,您可以导入它来保存所有面向公众的 Amplify 数据,但大多数人只会在 `.config` 中使用它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
这个过程需要一些时间来为您配置所有资源,所以趁此机会我们可以先设置我们的代码。
深入 Flutter 代码
在内部./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
然后,我们可以在主页中编写 Amplify 配置代码:
// 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需要添加一个加载画面。
对于应用程序的其余部分,您需要自己编写 Flutter UI 体验,但编写 Amplify 代码的困难部分已经结束了。
在小部件中使用 Amplify Auth
根据需要调用相应的函数(文档在此)。以下是用户登录的方法:
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
在小部件中使用 Amplify Storage
根据需要调用相应的函数(文档在此)。以下是上传新图片的方法:
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,Flutter 开发者预览版的功能与 JS/Android/iOS SDK 相比肯定存在不足。以下是未来几个月即将推出的功能:
- API(REST/GraphQL):API 类别提供了一个接口,用于检索和持久化您的数据,使用由 AWS AppSync 支持的 GraphQL 或使用 Amazon API Gateway 和 AWS Lambda 的 REST API 和处理程序。
- DataStore:Amplify DataStore 提供了一种编程模型,用于利用共享和分布式数据,而无需为离线和在线场景编写额外的代码,这使得处理分布式、跨用户数据与处理仅限本地的数据一样简单。
- 预测:预测类别支持前端 AI/ML 用例,例如翻译文本、将文本转换为语音以及识别图像中的文本、标签和人脸。
- 身份验证:我们将扩展身份验证类别,通过 Web 用户界面添加社交登录功能。
- 存储:我们将扩展存储类别,使其具备跟踪上传和下载进度的功能。
- 逃生舱:我们将添加对“逃生舱”的支持,使开发人员能够更轻松地使用底层生成的 iOS 和 Android AWS 移动 SDK 来实现更多用例。