How to Authenticate Before Uploading Files to Firebase
Building an Idea Tracker awarding with Flutter and Firebase
Learn how to implement Firebase components in Flutter by building an idea tracker application that helps users track new business ideas/opportunities, offers options to upload and fetch documents specific to each idea.
Flutter is a toolkit made by Google for building cross-platform apps easily.
Firebase is a Google product which helps developers to build, manage, and grow their apps easily. It comes with a host of pre-packaged services that saves developers a lot of hassle and time. Some of Firebase features are: User authentication using FireBase Authentication,NoSQL realtime database using Cloud FireStore, File Storage using Firebase Storage etc. We'll utilise these features to build our application.
In this tutorial I will show how to build an idea tracker awarding with 4 screens:
- Splash Screen: This custom splash screen will be used as the splash screen for this awarding.
- Welcome Screen: This screen will exist used to take user telephone number as input and authenticate them using Firebase Authentication.Each time a user tries to login, Firebase will ship a unique 6 digit authentication code to entered phone number. Upon hallmark user volition be redirected to his/her own DashBoard.
- DashBoard: This is the default screen that will be shown if a user has already logged in to the awarding in any previous instance.Users accept the option to view existing ideas, add together new ideas, update/delete existing ones and upload new documents to Firebase Storage for each thought.
- View Files Screen: This screen volition be used to show the documents uploaded by each user. Each View Files Screen is unique for each existing idea. Users accept the option to download and delete documents from this screen.
1. Pre-requisites
- Before getting started, brand sure that you lot install Flutter on your machine. You tin do information technology by post-obit the Flutter installation guide.
- i. Create a new Flutter project and remove all unnecessary lawmaking.
flutter create idea_tracker
ii. Or you tin can clone the GitHub repository from: thought tracker repository.
3. Add the packages mentioned in step 1.2. to pubspec.yaml file and run:
flutter pub go
4. The nextstep is to login to Firebase using your Google account and create a new Firebase app. You can add together the firebase app to your flutter project past post-obit the steps mentioned in Firebase setup with Palpitate.
1.1. Project Files Structure
Lib // root binder of all dart files in a Palpitate app
|_ services
|____ dbservice.dart
|____ deleteanddownloadfiles.dart
|____ getcloudfiles.dart
|____ uploadfiles.dart |_ components
|____ addtask.sprint
|____ cloudfiles.dart
|____ ideacount.dart
|____ idealist.dart
|____ rounded_button.sprint
|____ select_priority.dart
|____ sidenavigation.dart
|____ updatetask.dart |_ screens
|____ chooselogin.dart
|____ dashboard.dart
|____ splash_screen.dart
|____ viewfiles.dart
|____ welcomescreen.dart |_ utilities
|____ constants.dart |_ principal.dart
This is how our project structure will look similar. We volition go on UI components split from UI screens by creating divide directories.Reading/writing into services will exist handled separately by creating dart files under services directory.All the reusable constants(different textstyles) will be divers in constants.dart file under utilities directory.
1.2. Packages and dependencies
In Flutter, we can import tertiary-party packages in our project to add extra functionality without the need to create those functionality from scratch. The pub.dev website contains a listing of flutter packages which you can use in your projection. To use a bundle we just have to add the package name and version in the pubspec.yaml
file every bit follows. Go ahead and add the below dependancies in your file.
firebase_auth: ^one.2.0
cloud_firestore: ^2.2.0
firebase_core: ^1.2.0
animated_text_kit: ^4.ii.1
loading_overlay: ^0.3.0
font_awesome_flutter: ^9.0.0
flutter_slidable: ^0.6.0
firebase_storage: ^8.1.1
file_picker: ^iii.0.2+2
url_launcher: ^6.0.6
- firebase_auth : This packet is used to implement Firebase Authentication in Palpitate. We will use hallmark API from this package to sign in using our phone number and check for current user.
- cloud_firestore : This packet is used to implement Cloud FireStore in Flutter. We volition utilize FireStore APIs to store ideas in FireStore DB in form of collections as well every bit perform update/delete operations on them.
- firebase_core : This package is used to implement FireBase Core API in flutter. We will utilize this API to connect to our FireBase application.
- animated_text_kit : Comes with prepackaged text animations. We will utilise this in our Welcome Screen to display a text blitheness instead of building ane from scratch.
- loading_overlay : Provides a high level wrapper to employ Modal progress HUD. We will apply this to show a loading screen while authenticating users.
- font_awesome_flutter : Enables us to use the Font Crawly icon packs. We will apply the icons in our DashBoard to show an awesome logo on AppBar.
- flutter_slidable : Palpitate implementation of slidable listing detail with directional slide actions that can be dismissed. We will implement each idea every bit a Slidable widget with added options to update, delete, view and upload attachments.
- firebase_storage : This package provides united states with High level API to implement Firebase Storage in Flutter. We will use this API to upload, delete and call back attachments from Firebase Storage.
- file_picker: We will utilize this packet to implement native file explorer to selection files with added filtering support for extensions i.e; PDF.
- url_launcher: We will use this parcel to launch download URLs fetched from Firebase Storage into browser. The browser will take care of the file download.
2. Building the Welcome Screen and Phone Number Authentication
ii.1. Displaying text animation for app name in Welcome Screen:In the welcome screen we are going to ready up a pre-packaged text animation using TypewriterAnimatedText from animated_text_kit.Below is the code snippet where we utilise this widget to display the text blitheness.
2.2. Building Phone Authentication system: Setting up telephone authentication using FireBase in Flutter has been vividly documented in Palpitate Fire website. We will use "Firebaseauth.verifyPhoneNumber" to authenticate users using phone number. This process requires four parameters:
ii.one. phoneNumber: You provide the telephone number.
2.2. verificationCompleted: Define steps to follow after verification is completed.
2.iii. timeout: Ready a duration for validity on an OTP.
two.iv. codeSent: Define steps after code is sent to user for further validation.Within codeSent, we will create an AuthCredential object using the verification code entered and phone number to sign in to out awarding.
2.5. codeAutoRetrievalTimeout: Handle a timeout, when automatic SMS code treatment fails.
The entire code snippet can exist plant below:
2.3. Displaying a loading screen while user is being authenticated: We will use a LoadingOverlay widget to prove a Modal HUD while authenticating the user. The widget is rendered past using "_saving" variable. While authenticating nosotros set up this aspect to true within setState((){}) which renders the Modal HUD.
3. Building the DashBoard
3.i. Adding new ideas: New ideas will exist added using a BottomSheet widget, the code snippet for which tin be found in: Add Task Widget.
iii.i.one. Creating a course to create/update and delete data from FireStore:Brand certain you take created a new collection in Cloud FireStore before proceeding further.In my instance, the name of this drove is "ideacollection".
We will create a form in services/dbservice.sprint to add new ideas, as well as delete/update existing ideas from "ideacollection".We will create three fields for each document record in "ideacollection".These fields are:
3.ane.1.1. idea: Idea name.
3.1.one.2. priority: Priority can be 'High', 'Normal' and 'Depression'. This is selected by user in a dropdown menu present in Add together Task Widget.
three.one.1.3. user: The phone-number of a user will be sent in this field to create user-specific records.
Beneath is the lawmaking snippet to add, delete and update ideas in FireStore collection:
3.2. Viewing the ideas: We will utilize StreamBuilder in DashBoard to fetch ideas from FireStore Cloud for our logged in user. This provides realtime view of all ideas with improver, deletion or update to new ideas. Code snippet for viewing the data using StreamBuilder can be found below:
3.3. Implementing each idea every bit a Slidable Widget: Nosotros will implement each idea as a slidable widget. Upon sliding, user will exist presented with 4 options:
iii.three.one. Update idea: Use a lesser sheet widget similar to Add Task Widget, to update idea. Click here to access the Update Task Widget. Data volition be updated in FireStore drove using updateIdea role from DBStorage class we created earlier.
3.3.2. Delete idea: Tapping on this option will invoke the deleteIdea function from DBStorage class, which volition delete the document record from "ideacollection".
3.three.3. Upload attachments: We will create a new sprint file in services directory with a class UploadFiles to prompt users to pick a document from FileExplorer of the device, which and so volition be uploaded to FirebaseStorage.
3.3.3.1. We volition utilize FilePicker.platform.pickFiles from file_picker package to pick files from file explorer.
3.3.3.2. Past default, FireBaseStorage has no provisions to store user specific information for an awarding. Nosotros volition utilize a custom logic, where we create a directory for each user, and a subdirectory for each idea and upload documents related to that idea in the directory. The documents will exist uploaded in the following directory:
/<user_name>/<idea_name>/<your filename>
3.3.three.iii. Uploading files to FirebaseStorage requires no actress setup to be done from our side. For uploading the fetched file, we will use storage.ref(your directory name).putfile(filename) from firebase_storage package to upload the file to FireBase Storage.
Beneath is the Code snippet for UploadFiles class:
3.three.iv. View Uploaded Attachments: On tapping this option, user will be redirected to View Files Screen where user can view all the uploaded attachments for an idea.
Below is the code snippet for Slidable widget implementation:
4. Building the View Files Screen
We volition create a new ViewFiles widget to call back uploaded attachments from Firebase Storage using a FutureBuilder. Now why use FutureBuilder instead of StreamBuilder? It's because FirebaseStorage doesn't provide realtime data similar Cloud FireStore. We will use a FutureBuilder and invoke the getFileNames() method from GetCloudFiles() course(created nether services directory) to think filepath for each files.
Below is the lawmaking snippet for GetCloudFiles() form:
Code snippet to utilise FutureBuilder to display filenames is as follows:
For each attachment shown in ViewFiles widget, we will provide the user with two options:
4.ane. Download attachments: Nosotros will create a new dart(deleteanddownloadfiles.sprint) file in services directory with class DeleteandDownloadFiles to delete and download attachments.
For downloading attachments, we volition think the download URL for that zipper using FirebaseStorage.case.ref(<filepath>).getDownloadURL().
We will then open this URL in browser using launch(<download URL>) function from url_launcher package. The browser will take care of the download process.
Beneath is the code snippet to fetch download URL and download files from FireBase Storage:
4.ii. Delete Attachments: In DeleteandDownloadFiles class we will create another method deletefromStorage() to delete the attachments from FireBase Storage using FireBaseStorage.instance.ref(<filepath>).delete().
Below is the code snippet to delete the attachments from Firebase Storage:
We accept now learnt how to download and delete files from FireBase Storage. But, do you think that ViewFiles widget will perfectly show the updated listing of attachments on deleting one? The short answer is it won't.
FutureBuilder widget will listen only once for the async data and build the list.The list of attachments is built using the async snapshot received from FutureBuilder. Nosotros solve this problem and brand the FutureBuilder behave like a StreamBuilder past periodically invoking the setState(){<Variable proper name for list of attachments >} to forcefulness the FutureBuilder to periodically remember filenames from FireBase Storage and rebuild the listing.
Below is the code snippet to periodically listen to FirebaseStorage data and rebuild the listing:
5. Decision
- The full source lawmaking for this project is bachelor here.
- Well-nigh of complex back-stop work like authentication, database direction and files storage can be handled by FireBase with footling configurations and tweaks. Click to read more on Firebase Integration with Flutter.
- Learn more on Stream and Futures from this youtube video from official Flutter channel.
herzogtogglike1993.blogspot.com
Source: https://medium.com/geekculture/building-an-idea-tracker-application-with-flutter-and-firebase-4474a9f87ad6
0 Response to "How to Authenticate Before Uploading Files to Firebase"
Postar um comentário