avatarAseem Wangoo

Summary

The website content provides a comprehensive guide on integrating Flutter with Amazon Web Services (AWS) for file storage and retrieval, utilizing services like S3 and Lambda.

Abstract

The provided content delves into the integration of Flutter applications with AWS services as an alternative to Firebase. It offers a step-by-step tutorial on setting up an Amazon S3 bucket for file storage, configuring AWS Lambda for serverless computing, and deploying APIs to facilitate file operations from a Flutter app. The guide emphasizes the use of the serverless package for creating and managing AWS Lambda functions and covers the necessary AWS configurations, including bucket policy adjustments for public access and the setup of AWS credentials. It also includes code snippets for handling file uploads and retrievals, and references additional resources for Flutter development with AWS services.

Opinions

  • The author suggests AWS as a robust alternative to Firebase for Flutter developers.
  • The use of AWS Lambda and S3 is presented as a seamless way to handle backend operations for Flutter apps.
  • The guide acknowledges the need for organizations to have alternatives to Firebase, indicating a preference for AWS within the Flutter community.
  • The tutorial implies that the combination of Flutter and AWS provides a scalable and efficient solution for mobile and web applications.
  • By providing a video tutorial for setting up AWS credentials, the author indicates that this step might be complex for some developers and requires additional guidance.
  • The inclusion of a public bucket policy template suggests that public access to S3 resources is a common requirement for developers.
  • The author emphasizes the importance of proper AWS configurations to ensure secure and successful integration with Flutter applications.

Flutter and AWS

Flutter and AWS

What if our organization does not want to use Firebase ? Hmmm…..

All in one Flutter resource: https://flatteredwithflutter.com/how-to-use-flutter-and-aws-s3-bucket/

This article sneak peeks into the world of Amazon, typically AWS

Prerequisite…

Flutter and AWS

For the programming of this demo, we have used

  1. Amazon s3 Bucket
  2. Amazon Lambda Functions
  3. Obviously Flutter :p

Step 1:

Create an account on Amazon Developer Console

Step 2:

Search for s3 in the Management console…

AWS Console…

Create Bucket as per your choice…

By default the bucket is not public, so we need to make it…

Click on your bucket name (aseemwangoobucket) in my case….

s3 public access…

Click on Permissions Tab…

Turn off (Block all public access)…

Public access…

Next, go to Bucket policy…. and paste below

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1405592139000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::'NAME OF YOUR BUCKET'/*",
                "arn:aws:s3:::'NAME OF YOUR BUCKET'"
            ]
        }
    ]
}

NOTE : Replace ‘NAME OF YOUR BUCKET’ with your bucket name…

This allows us to perform operations of any type on our bucket…

Step 3 :

We need to make APIs in order to perform operations on the bucket.

To make APIs, AWS offers Lambda similar to Cloud Functions….

Go to AWS Console and search for Lambda….

AWS Lambda…

How to write and deploy Lambdas…

  1. Install serverless: This is a nodeJS package which helps us to write Lambdas and deploy them onto AWS
npm install -g serverless

2. Set up your AWS credentials…..(Follow this video)

serverless config credentials --provider aws --key 'YOUR AWS KEY' --secret 'YOUR AWS SECRET'

You should get output as

Serverless: Setting up AWS...
Serverless: Saving your AWS profile in "~/.aws/credentials"...
Serverless: Success! Your AWS access keys were stored under the "default" profile.

3. Create a project (serverless)

# Create a new Serverless Service/Project
serverless create --template aws-nodejs

handler.js -> Where you write your logic...

serverless.yml -> Where you describe your deployment...

functions:

  getAllFiles:
    handler: handler.getAllFiles
    events:
     - http:
         path: /getAllFiles
         method: get       

  uploadFile:
    handler: handler.uploadFile
    events:
     - http:
         path: /uploadFile
         method: post

For instance, get and post url endpoints….

In the handler.js file…

Logic for getting all Files, from AWS storage…

module.exports.getAllFiles = async (event, context) => {

  let files = [];

  let params = {
    Bucket: process.env.BUCKET, /* required */
    Prefix: 'upload'
  };

  let result = await s3.listObjectsV2(params).promise();

  let data = result.Contents;
  Object.keys(data).forEach((key, index) => {

    let fileObject = data[key];

    files.push(`https://${result.Name}.s3.us-east-2.amazonaws.com/${fileObject.Key}`);
  });


  return {
    statusCode: 200,
    body: JSON.stringify({
      files: files,
      bucketName: `${result.Name}`,
      subFolder: `${result.Prefix}`,
    }, null, 2),
  };
};

Logic for uploading files to bucket…

module.exports.uploadFile = async (event, context) => {

  let request = event.body;
  let jsonData = JSON.parse(request);
  let base64String = jsonData.base64String;
  let buffer = Buffer.from(base64String, 'base64');
  let fileMime = fileType(buffer);

  if (fileMime == null) {
    return context.fail('The string supplied is not a file type.');
  }

  let file = getFile(fileMime, buffer); 
//Extract file info in getFile
//File.params would have
//{'params': params,uploadFile': uploadFile};
  let params = file.params;

  let result = await s3.putObject(params).promise();

  return {
    statusCode: 200,
    body: JSON.stringify({
      url: `${file.uploadFile.full_path}`,
    }, null, 2),
  };
};
Flutter and AWS….

Note : Files will be saved or deleted from the S3 bucket, which you set earlier….

4. For deploying

serverless deploy

This gives you the REST Url……

5. You can use this URL in the Flutter App for fetching, uploading, or deleting files from the S3 bucket….

Note : You don’t need to deploy separately for getting different urls. Just deploy once and you will get the endpoints on the basis of your serverless.yaml file

Articles related to Flutter:

AWS
Flutter
Dart
Mobile App Development
Programming
Recommended from ReadMedium