Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

CodeSearchOnline

Flutter Firebase cheat sheet 🔥


Published by Abhay Rastogi on 26th December 2019

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.

  
https://codesearchonline.com/flutter-firebase/ 1/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

CodeSearchOnline

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).

  
https://codesearchonline.com/flutter-firebase/ 2/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

Contents [ hide ]
CodeSearchOnline
1 Flutter Firebase Authentication
1.1 Email And Password-based Authentication
1.1.1 Register User
1.1.2 Login user
1.2 Flutter Firebase Phone Authentication
2 Flutter Firebase Cloud firestore
3 Flutter Firebase Storage
4 Firebase Push notification(Cloud Messaging)
4.1 Device to device notification
4.2 Topic Subscription

Mac/Linux

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

Windows

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

Download google_services.json

  
https://codesearchonline.com/flutter-firebase/ 3/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

CodeSearchOnline

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

  
https://codesearchonline.com/flutter-firebase/ 4/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

FirebaseUser user;
CodeSearchOnline
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
}
}
}

Flutter Firebase Phone Authentication


Firebase phone authentication is the most common way for authenticating users. flutter firebase phone
authentication is easy to implement.

String Phonenumber='+91738XXXX';
String _Otpnumber='38XXXX';

GestureDetector(
onTap: () async { _verifyPhoneNumber(Phonenumber); },

GestureDetector(
onTap: () async { PhoneAuthentication(_Otpnumber); },

PhoneAuthentication(String Otp){
  
https://codesearchonline.com/flutter-firebase/ 5/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

_signInWithPhoneNumber(Otp).then((FirebaseUser user) {
CodeSearchOnline
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);

};

  
https://codesearchonline.com/flutter-firebase/ 6/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥
final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
CodeSearchOnline
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 _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

Stunning Resort Destinations


Choose a Resort Where Everyone Can Do What They
Love.

Ad MARRIOTT BONVOY Open

  
https://codesearchonline.com/flutter-firebase/ 7/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

_getCurrentUserDetail() async {
CodeSearchOnline
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 cloud firestore we can perform
complex Querys such as AND, OR, EQUAL TO very easily. data can be added modified or deleted in Flutter
Firebase Cloud Firestore 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',
}

Update data

Firestore.instance.collection('Message')
.document(docId)
.updateData(
{
'description':'description1',
}
  
https://codesearchonline.com/flutter-firebase/ 8/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

Delete data
CodeSearchOnline

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'];
});

}));
});

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);
}

});

Flutter Firebase

Storage  
https://codesearchonline.com/flutter-firebase/ 9/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

For storing files in firebase provided its own storing services. In this Flutter Firebase Storage we will see
CodeSearchOnline
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

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;
});
}
);
}
}

Firebase Push notification(Cloud Messaging)


We can send app notifications in a flutter by using a firebase cloud messaging service in a flutter. In this,
we will see how we can send notifications from one device to another ie. device to device notification and
  
https://codesearchonline.com/flutter-firebase/ 10/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

notification with a topic subscription. we also need the Server key of cloud messaging you can get it from
CodeSearchOnline
project settings in the cloud messaging tab.

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();
}

Futuresend_notification(String send_uid) async{

Firestore.instance
  
https://codesearchonline.com/flutter-firebase/ 11/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥
.collection('user')
.where('ID', isEqualTo: send_uid)
CodeSearchOnline
.snapshots()
.listen((data) => data.documents.forEach((doc) {

fcm = ['fcmTocken'].toString();
sendfcm(_token) ;

}));
}
}

Futuresendfcm(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.
  
https://codesearchonline.com/flutter-firebase/ 12/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

import 'package:firebase_messaging/firebase_messaging.dart';
CodeSearchOnline
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;

@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.subscribeToTopic('Tech_News');
_firebaseMessaging.subscribeToTopic('All_News');
// TODO: implement initState
super.initState();
}

Futuresendfcm() 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": "/topics/All_News"
};
final headers = {
'content-type': 'application/json',
'Authorization': key
};

 = await http.post(postUrl,
final response  
https://codesearchonline.com/flutter-firebase/ 13/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
CodeSearchOnline
headers: headers);

if (response.statusCode == 200) {
print("Notification send !");
} else {
print("false");
}
}
}
}

Categories: FLUTTER FIREBASE

Tags: authentication cloud storage cloudfirestore notification

2 Comments

8511 respirator · 3rd April 2020 at 10:07 am

Hello. This post was extremely interesting, particularly because I was looking for thoughts on this
topic last Thursday.
Best regards,
Balle Griffin

REPLY

moviedailynews · 25th November 2021 at 7:27 am

I pay a quick visit every day a few sites and websites to read content,
but this website offers feature-based content.

REPLY

Leave a Reply
  
https://codesearchonline.com/flutter-firebase/ 14/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

Name *
CodeSearchOnline

Email *

Website

What's on your mind?

Save my name, email, and website in this browser for the next time I comment.

POST COMMENT

Search …

Recent Posts

Flutter AppBar (Cheat Sheet)

Natural language processing With Tensorflow

5 Tensorflow Callbacks for Quick and Easy Training

4 Best Web Hosting for WordPress Websites

Google Hosting For WordPress On GCP

  
https://codesearchonline.com/flutter-firebase/ 15/19
®koobe
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

®koobecaF
CodeSearchOnline

Connect
With
Your
Friends
Check Out The Newest
Features To Keep In
Touch With Friends And
Family!
Facebook®

Sign Up

Related Posts

  
https://codesearchonline.com/flutter-firebase/ 16/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

CodeSearchOnline

FLUTTER

Flutter AppBar (Cheat Sheet)


Flutter AppBar is a material design widget in Flutter that gives the application a visual structure. It is a type of
toolbar that is used to provide a consistent user interface across different screens. It Read more…

  
https://codesearchonline.com/flutter-firebase/ 17/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

CodeSearchOnline

FLUTTER

Flutter Form Textfield Validation


This Flutter Form Textfield Validation describes the validations methods that your application may require. The
most crucial thing to accomplish before submitting the text written by the user and informing them of an error
message Read more…

  
https://codesearchonline.com/flutter-firebase/ 18/19
12/17/22, 8:10 PM Flutter Firebase Cheat Sheet 🔥 » CodeSearchOnline Flutter Firebase Cheat Sheet 🔥

CodeSearchOnline

FLUTTER

Read And Write CSV File In Flutter(Web, Mobile)


In Flutter, you can read and write CSV files. We must ensure a couple of things. The most important aspect of
reading the CSV file is loading it into Flutter, and for that, we can Read more…

PRIVACY POLICY REFUND POLICY CONTACT US

CodeSearchOnline

  
https://codesearchonline.com/flutter-firebase/ 19/19

You might also like