Flutter Firebase Cheat Sheet! 🔥 Published by on

Flutter Firebase Cheat Sheet covers firebase service for the rapid development of flutter applications such as Authentication, posting data and retrieving data from cloud firestore, Uploading an image(cloud storage) on firebase and Push notification(device to device and topic subscription) by firebase messaging.

Firebase is a development platform created by firebase which is currently managed google. firebase provides a variety of tools and services for rapid development.

We have to set up firebase SDK in flutter before using any of its services. create new Firebase project then select android plate form.

Enter app package name copy it from android/app/src/main/AndroidManifest.xml you can also give app nickname that is totally optional. but make sure of entering SHA-1 as it’s required for authentication.you can get your SHA-1 just copy the below code in the terminal for more details(client-auth).

Mac/Linux

keytool -list -v \ -alias androiddebugkey -keystore ~/.android/debug.keystore 1 2 keytool - list - v \ - alias androiddebugkey - keystore ~ / . android / debug . keystore

Windows

keytool -list -v \ -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore 1 2 keytool - list - v \ - alias androiddebugkey - keystore % USERPROFILE % \ . android \ debug . keystore

Download google_services.json

Flutter Firebase Authentication

Authentication is required to be implemented in most of the applications for authorizing users to access flutter screens. firebase gives a variety of authentication options. In this blog email, password and phone authentication.

Add dependencies: firebase_auth: in pubspec.yaml file then install it by flutter pub get in your terminal and import ‘package:firebase_auth/firebase_auth.dart’; in your dart file.more detail(https://pub.dev/packages/firebase_auth#-installing-tab-)

Email And Password-based Authentication

Register User

FirebaseUser user; void _registerUser(String _email,String _password) async { user = (await _auth.createUserWithEmailAndPassword( email: _email, password: _password, )).user; if (user != null) { // User registered successfully // Add user details in realtime database or cloudfirestore } else { // User not registered Successfully } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 FirebaseUser user ; void _registerUser ( String _email , String _password ) async { user = ( await _auth . createUserWithEmailAndPassword ( email : _email , password : _password , ) ) . user ; if ( user != null ) { // User registered successfully // Add user details in realtime database or cloudfirestore } else { // User not registered Successfully } } }

Login user

final FirebaseUser user void _signInWithEmailAndPassword(String _email,String _password) async { user = (await _auth.signInWithEmailAndPassword( email: _email, password: _password, )).user; if (user != null) { // Login successful // Navigate to main page } else { // Invalid email and password // Navigate to registration page } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 final FirebaseUser user void _signInWithEmailAndPassword ( String _email , String _password ) async { user = ( await _auth . signInWithEmailAndPassword ( email : _email , password : _password , ) ) . user ; if ( user != null ) { // Login successful // Navigate to main page } else { // Invalid email and password // Navigate to registration page } } }

Flutter Firebase Phone Authentication

String Phonenumber='+91738XXXX'; String _Otpnumber='38XXXX'; GestureDetector( onTap: () async { _verifyPhoneNumber(Phonenumber); }, GestureDetector( onTap: () async { PhoneAuthentication(_Otpnumber); }, PhoneAuthentication(String Otp){ _signInWithPhoneNumber(Otp).then((FirebaseUser user) { Navigator.push( context, MaterialPageRoute(builder: (context) => Dashboard())); Toast.show("Successfully signed in", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); }).catchError((e) { print(e.code); switch (e.code) { case 'ERROR_INVALID_VERIFICATION_CODE': Toast.show('INVALID VERIFICATION CODE', context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); print('Code is invalid'); break; case 'ERROR_SESSION_EXPIRED': Toast.show('INVALID VERIFICATION CODE', context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); print('Code is invalid'); break; default: } }); } } void _verifyPhoneNumber() async { setState(() { _message = ''; }); final PhoneVerificationCompleted verificationCompleted = (AuthCredential phoneAuthCredential) { _auth.signInWithCredential(phoneAuthCredential); Toast.show('Received phone auth credential', context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); }; final PhoneVerificationFailed verificationFailed = (AuthException authException) { Toast.show('Phone number verification failed', context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); }; final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async { Toast.show("Please check your phone for the verification code", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); this._verificationId = verificationId; }; final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) { this._verificationId = verificationId; }; await _auth.verifyPhoneNumber( phoneNumber: widget.phoneNumber, timeout: const Duration(seconds: 20), verificationCompleted: verificationCompleted, verificationFailed: verificationFailed, codeSent: codeSent, codeAutoRetrievalTimeout: codeAutoRetrievalTimeout); } Future<FirebaseUser> _signInWithPhoneNumber(String _Otpnumber) async { final AuthCredential credential = PhoneAuthProvider.getCredential( verificationId: _verificationId, smsCode: _Otpnumber, ); print(credential); final FirebaseUser user = (await _auth.signInWithCredential(credential)).user; final FirebaseUser currentUser = await _auth.currentUser(); assert(user.uid == currentUser.uid); return user; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 String Phonenumber = '+91738XXXX' ; String _Otpnumber = '38XXXX' ; GestureDetector ( onTap : ( ) async { _verifyPhoneNumber ( Phonenumber ) ; } , GestureDetector ( onTap : ( ) async { PhoneAuthentication ( _Otpnumber ) ; } , PhoneAuthentication ( String Otp ) { _signInWithPhoneNumber ( Otp ) . then ( ( FirebaseUser user ) { Navigator . push ( context , MaterialPageRoute ( builder : ( context ) = > Dashboard ( ) ) ) ; Toast . show ( "Successfully signed in" , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; } ) . catchError ( ( e ) { print ( e . code ) ; switch ( e . code ) { case 'ERROR_INVALID_VERIFICATION_CODE' : Toast . show ( 'INVALID VERIFICATION CODE' , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; print ( 'Code is invalid' ) ; break ; case 'ERROR_SESSION_EXPIRED' : Toast . show ( 'INVALID VERIFICATION CODE' , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; print ( 'Code is invalid' ) ; break ; default : } } ) ; } } void _verifyPhoneNumber ( ) async { setState ( ( ) { _message = '' ; } ) ; final PhoneVerificationCompleted verificationCompleted = ( AuthCredential phoneAuthCredential ) { _auth . signInWithCredential ( phoneAuthCredential ) ; Toast . show ( 'Received phone auth credential' , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; } ; final PhoneVerificationFailed verificationFailed = ( AuthException authException ) { Toast . show ( 'Phone number verification failed' , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; } ; final PhoneCodeSent codeSent = ( String verificationId , [ int forceResendingToken ] ) async { Toast . show ( "Please check your phone for the verification code" , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; this . _verificationId = verificationId ; } ; final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = ( String verificationId ) { this . _verificationId = verificationId ; } ; await _auth . verifyPhoneNumber ( phoneNumber : widget . phoneNumber , timeout : const Duration ( seconds : 20 ) , verificationCompleted : verificationCompleted , verificationFailed : verificationFailed , codeSent : codeSent , codeAutoRetrievalTimeout : codeAutoRetrievalTimeout ) ; } Future < FirebaseUser > _signInWithPhoneNumber ( String _Otpnumber ) async { final AuthCredential credential = PhoneAuthProvider . getCredential ( verificationId : _verificationId , smsCode : _Otpnumber , ) ; print ( credential ) ; final FirebaseUser user = ( await _auth . signInWithCredential ( credential ) ) . user ; final FirebaseUser currentUser = await _auth . currentUser ( ) ; assert ( user . uid == currentUser . uid ) ; return user ; } }

Check current user detail

_getCurrentUserDetail() async { await FirebaseAuth.instance.currentUser().then((user){ if(user!=null){ print(user.uid.toString()); print(user.name); print(user.email); print("yes"); rout_Dashboard(); }else{ print("no"); rout_Signin(); } }); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 _getCurrentUserDetail ( ) async { await FirebaseAuth . instance . currentUser ( ) . then ( ( user ) { if ( user != null ) { print ( user . uid . toString ( ) ) ; print ( user . name ) ; print ( user . email ) ; print ( "yes" ) ; rout_Dashboard ( ) ; } else { print ( "no" ) ; rout_Signin ( ) ; } } ) ; }

Flutter Firebase Cloud firestore

Firebase gives you the power of storing data in NoSQL formate.in cloudfirestore we can perform complex Querys such as AND, OR, EQUAL TO very easily. data can be added modified or deleted in CloudFirestore in realtime.

Add dependencies: cloud_firestore: in pubspec.yaml file then install it by flutter pub get in your terminal and import ‘package:cloud_firestore/cloud_firestore.dart’;in your dart file more detail(cloud_firestore).

Add data

import 'package:intl/intl.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; Firestore.instance.collection('Message') .document('message'+DateTime.now().microsecondsSinceEpoch.toString()) .setData( { 'type':'msg', 'subject':'sub', 'description':'description', 'to':'user1', 'from':'uid', } 1 2 3 4 5 6 7 8 9 10 11 import 'package:intl/intl.dart' ; import 'package:cloud_firestore/cloud_firestore.dart' ; Firestore . instance . collection ( 'Message' ) . document ( 'message' + DateTime . now ( ) . microsecondsSinceEpoch . toString ( ) ) . setData ( { 'type' : 'msg' , 'subject' : 'sub' , 'description' : 'description' , 'to' : 'user1' , 'from' : 'uid' , }

Update data

Firestore.instance.collection('Message') .document(docId) .updateData( { 'description':'description1', } 1 2 3 4 5 6 Firestore . instance . collection ( 'Message' ) . document ( docId ) . updateData ( { 'description' : 'description1' , }

Delete data

Firestore.instance.collection('Message').document(docId).delete() 1 Firestore . instance . collection ( 'Message' ) . document ( docId ) . delete ( )

Fetch data

Firestore.instance .collection('user') .where('from', isEqualTo: uid) .snapshots() .listen((data) => data.documents.forEach((doc) { setState(() { message = doc['id']; }); })); }); 1 2 3 4 5 6 7 8 9 10 11 12 Firestore . instance . collection ( 'user' ) . where ( 'from' , isEqualTo : uid ) . snapshots ( ) . listen ( ( data ) = > data . documents . forEach ( ( doc ) { setState ( ( ) { message = doc & #91;'id']; } ) ; } ) ) ; } ) ;

Check if data exists in cloudfirestore!

Query colRef = Firestore.instance .collection('user') .where('mobile', isEqualTo:_phoneNumber) .where('type',isEqualTo:'editor'); colRef.getDocuments().then((data){ if(data.documents.isNotEmpty){ data.documents.forEach((data){ print(data['Name']); }); Toast.show("authorize User", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); } else{ Toast.show("Unauthorize User", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM); } }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Query colRef = Firestore . instance . collection ( 'user' ) . where ( 'mobile' , isEqualTo : _phoneNumber ) . where ( 'type' , isEqualTo : 'editor' ) ; colRef . getDocuments ( ) . then ( ( data ) { if ( data . documents . isNotEmpty ) { data . documents . forEach ( ( data ) { print ( data & #91;'Name']); } ) ; Toast . show ( "authorize User" , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; } else { Toast . show ( "Unauthorize User" , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; } } ) ;

Flutter Firebase Storage

For storing files in firebase provided its own storing services. In this we will see how we can store the image in firebase storage for that we have to use one more plugin to get a file path either from the camera or gallery of the phone.

//Add this to your package's pubspec.yaml file dependencies: image_picker: ^0.6.2+3 firebase_storage: ^3.1.0 1 2 3 4 //Add this to your package's pubspec.yaml file dependencies : image_picker : ^ 0.6.2 + 3 firebase_storage : ^ 3.1.0

upload.dart

import 'package:image_picker/image_picker.dart'; import 'package:firebase_storage/firebase_storage.dart'; Future getImage() async { var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery); filePath = (tempImage.path); final StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName); final StorageUploadTask task = firebaseStorageRef.putFile(sampleImage); await (await task.onComplete).ref.getDownloadURL().then((image){ var url = image.toString(); print("Downloaded url $url"); Firestore.instance.collection('user') .document(widget.UserId) .setData({'Image': url} ,merge:true); Toast.show("Image upload successfully",context,duration: Toast.LENGTH_LONG,gravity: Toast.BOTTOM); setState(() { _saving=false; }); } ); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import 'package:image_picker/image_picker.dart' ; import 'package:firebase_storage/firebase_storage.dart' ; Future getImage ( ) async { var tempImage = await ImagePicker . pickImage ( source : ImageSource . gallery ) ; filePath = ( tempImage . path ) ; final StorageReference firebaseStorageRef = FirebaseStorage . instance . ref ( ) . child ( fileName ) ; final StorageUploadTask task = firebaseStorageRef . putFile ( sampleImage ) ; await ( await task . onComplete ) . ref . getDownloadURL ( ) . then ( ( image ) { var url = image . toString ( ) ; print ( "Downloaded url $url" ) ; Firestore . instance . collection ( 'user' ) . document ( widget . UserId ) . setData ( { 'Image' : url } , merge : true ) ; Toast . show ( "Image upload successfully" , context , duration : Toast . LENGTH_LONG , gravity : Toast . BOTTOM ) ; setState ( ( ) { _saving = false ; } ) ; } ) ; } }

Firebase Push notification(Cloud Messaging)

We can send app notifications in a flutter by using a firebase cloud messaging service in flutter. In this, we will see how we can send notification from one device to other ie. device to device notification and notification with a topic subscription.we also need the Server key of cloud messaging you can get it from project settings in the cloud messaging tab.

dependencies: firebase_messaging: http: 1 2 3 dependencies : firebase_messaging : http :

Device to device notification

Before sending notification from one device to other we need to store the token in the database.

import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:http/http.dart' as http; import 'dart:async'; import 'dart:convert'; class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; String fcm; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); String key="your service key!"; final postUrl = 'https://fcm.googleapis.com/fcm/send'; @override void initState() { _firebaseMessaging.getToken().then((_key){ print(_key); //Save this fcm token in CloudfireStore or in realtime database! Firestore.instance.collection("user").document(uid).setData({ "fcmTocken":_key },merge: true); }); // TODO: implement initState super.initState(); } Future<void>send_notification(String send_uid) async{ Firestore.instance .collection('user') .where('ID', isEqualTo: send_uid) .snapshots() .listen((data) => data.documents.forEach((doc) { fcm = ['fcmTocken'].toString(); sendfcm(_token) ; })); } } Future<void>sendfcm(String fcm) async{ final postUrl = 'https://fcm.googleapis.com/fcm/send'; final data = { "notification": {"body": "CodeSearchOnline", "title": "Flutter Notification"}, "priority": "high", "data": { "click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done" }, "to": fcm }; final headers = { 'content-type': 'application/json', 'Authorization': key }; final response = await http.post(postUrl, body: json.encode(data), encoding: Encoding.getByName('utf-8'), headers: headers); if (response.statusCode == 200) { print("Notification send !"); } else { print("false"); } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 import 'package:firebase_messaging/firebase_messaging.dart' ; import 'package:http/http.dart' as http ; import 'dart:async' ; import 'dart:convert' ; class MyHomePage extends StatefulWidget { MyHomePage ( { Key key , this . title } ) : super ( key : key ) ; final String title ; String fcm ; @ override _MyHomePageState createState ( ) = > _MyHomePageState ( ) ; } class _MyHomePageState extends State & lt ; MyHomePage > { final FirebaseMessaging _firebaseMessaging = FirebaseMessaging ( ) ; String key = "your service key!" ; final postUrl = 'https://fcm.googleapis.com/fcm/send' ; @ override void initState ( ) { _firebaseMessaging . getToken ( ) . then ( ( _key ) { print ( _key ) ; //Save this fcm token in CloudfireStore or in realtime database! Firestore . instance . collection ( "user" ) . document ( uid ) . setData ( { "fcmTocken" : _key } , merge : true ) ; } ) ; // TODO: implement initState super . initState ( ) ; } Future < void > send_notification ( String send_uid ) async { Firestore . instance . collection ( 'user' ) . where ( 'ID' , isEqualTo : send_uid ) . snapshots ( ) . listen ( ( data ) = > data . documents . forEach ( ( doc ) { fcm = [ 'fcmTocken' ] . toString ( ) ; sendfcm ( _token ) ; } ) ) ; } } Future < void > sendfcm ( String fcm ) async { final postUrl = 'https://fcm.googleapis.com/fcm/send' ; final data = { "notification" : { "body" : "CodeSearchOnline" , "title" : "Flutter Notification" } , "priority" : "high" , "data" : { "click_action" : "FLUTTER_NOTIFICATION_CLICK" , "id" : "1" , "status" : "done" } , "to" : fcm } ; final headers = { 'content-type' : 'application/json' , 'Authorization' : key } ; final response = await http . post ( postUrl , body : json . encode ( data ) , encoding : Encoding . getByName ( 'utf-8' ) , headers : headers ) ; if ( response . statusCode == 200 ) { print ( "Notification send !" ) ; } else { print ( "false" ) ; } } } }

Topic Subscription

In topic subscription, we need to subscribe to a topic then send a notification on that topic added by the device.