06-Module 6

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

CSE431

Mobile Programming

MODULE 6:
CLOUD SERVICES: USING FIREBASE IN FLUTTER
Add Firebase to your Flutter app
• Step 1: Install the required command line tools

• If you haven't already done so, install the Firebase CLI.


https://firebase.google.com/docs/cli

• Log into Firebase using your Google account by running the


following command:

– firebase login

• Install the FlutterFire CLI by running the following command from


any directory:

– dart pub global activate flutterfire_cli


Add Firebase to your Flutter app
• Step 2: Configure your apps to use Firebase
• Use the FlutterFire CLI to configure your Flutter apps to connect to Firebase.

• From your Flutter project directory, run the following command to start the app
configuration workflow:

– flutterfire configure

After this initial running of flutterfire configure, you need to re-run the command any time that you:
• Start supporting a new platform in your Flutter app.
• Start using a new Firebase service or product in your Flutter app, especially if you start using sign-
in with Google, Crashlytics, Performance Monitoring, or Realtime Database.
• Re-running the command ensures that your Flutter app's Firebase configuration is up-to-date and
(for Android) automatically adds any required Gradle plugins to your app.
Add Firebase to your Flutter app
Step 3: Initialize Firebase in your app

1.From your Flutter project directory, run the following command to install the core plugin:
flutter pub add firebase_core

2.From your Flutter project directory, run the following command to ensure that your Flutter app's Firebase configuration is up-to-
date:
flutterfire configure

3.In your lib/main.dart file, import the Firebase core plugin and the configuration file you generated earlier:
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

4.Also in your lib/main.dart file, initialize Firebase using the DefaultFirebaseOptions object exported by the configuration file:
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);

5.Rebuild your Flutter application:


flutter run

If you would rather use a demo project, you can start the Firebase Emulator and in your lib/main.dart file initialize Firebase
using demoProjectId (it should start with demo-):
await Firebase.initializeApp(
demoProjectId: "demo-project-id",
);
Add Firebase to your Flutter app
Step 4: Add Firebase plugins

• You access Firebase in your Flutter app through the various Firebase Flutter plugins, one for
each Firebase product (for example: Cloud Firestore, Authentication, Analytics, etc.).
• Since Flutter is a multi-platform framework, each Firebase plugin is applicable for Apple,
Android, and web platforms. So, if you add any Firebase plugin to your Flutter app, it will be
used by the Apple, Android, and web versions of your app.
Here's how to add a Firebase Flutter plugin:
1.From your Flutter project directory, run the following command:
flutter pub add PLUGIN_NAME

2.From your Flutter project directory, run the following command:


flutterfire configure

Running this command ensures that your Flutter app's Firebase configuration is up-to-date and,
for Crashlytics and Performance Monitoring on Android, adds the required Gradle plugins to your
app.

3.Once complete, rebuild your Flutter project:


flutter run

You're all set! Your Flutter apps are registered and configured to use Firebase.
Add Firebase to your Flutter app
Add Firebase to your Flutter app
Firebase Authentication on Flutter

Firebase Auth provides many methods and utilities for enabling you to
integrate secure authentication into your new or existing Flutter
application. In many cases, you will need to know about the
authentication state of your user, such as whether they're logged in or
logged out.

Firebase Auth enables you to subscribe in realtime to this state via a


Stream. Once called, the stream provides an immediate event of the
user's current authentication state, and then provides subsequent
events whenever the authentication state changes.
Add Firebase to your Flutter app
Firebase Authentication on Flutter
There are three methods for listening to authentication state changes:

authStateChanges()
To subscribe to these changes, call the authStateChanges() method on
your FirebaseAuth instance

idTokenChanges()
To subscribe to these changes, call the idTokenChanges() method on your
FirebaseAuth instance

userChanges()
To subscribe to these changes, call the userChanges() method on your
FirebaseAuth instance

https://firebase.google.com/docs/auth/flutter/start
Add Firebase to your Flutter app
Firebase Authentication on Flutter

authStateChanges() .idTokenChanges() userChanges()


FirebaseAuth.instance
FirebaseAuth.instance FirebaseAuth.instance
.userChanges()
.authStateChanges() .idTokenChanges()
.listen((User? user) {
.listen((User? user) { .listen((User? user) {
if (user == null) {
if (user == null) { if (user == null) {
print('User is currently signed
print('User is currently signed out!'); print('User is currently signed
out!');
} else { out!');
} else {
print('User is signed in!'); } else {
print('User is signed in!');
} print('User is signed in!');
}
}); }
});
});

https://firebase.google.com/docs/auth/flutter/start
Add Firebase to your Flutter app
Persisting authentication state

The Firebase SDKs for all platforms provide out of the box support for ensuring
that your user's authentication state is persisted across app restarts or page
reloads.

On native platforms such as Android & iOS, this behavior is not configurable and
the user's authentication state will be persisted on device between app restarts.
The user can clear the apps cached data using the device settings, which will
wipe any existing state being stored.

On web platforms, the user's authentication state is stored in IndexedDB. You


can change the persistence to store data in the local storage using
Persistence.LOCAL. If required, you can change this default behavior to only
persist authentication state for the current session, or not at all. To configure
these settings, call the following method FirebaseAuth.instanceFor(app:
Firebase.app(), persistence: Persistence.LOCAL);. You can still update the
persistence for each Auth instance using setPersistence(Persistence.NONE).

https://firebase.google.com/docs/auth/flutter/start
Add Firebase to your Flutter app
Persisting authentication state

You can still update the persistence for each Auth instance using
setPersistence(Persistence.NONE).
// Disable persistence on web platforms. Must be called on initialization:
final auth = FirebaseAuth.instanceFor(app: Firebase.app(), persistence:
Persistence.NONE);
// To change it after initialization, use `setPersistence()`:
await auth.setPersistence(Persistence.LOCAL);

https://firebase.google.com/docs/auth/flutter/start
Add Firebase to your FlutterFirebase
appAuthentication on Flutter

authStateChanges()
Events are fired when the following occurs:
• Right after the listener has been registered.
• When a user is signed in.
• When the current user is signed out.

idTokenChanges()
Events are fired when the following occurs:
• Right after the listener has been registered.
• When a user is signed in.
• When the current user is signed out.
• When there is a change in the current user's token.

userChanges()
Events are fired when the following occurs:
• Right after the listener has been registered.
• When a user is signed in.
• When the current user is signed out.
• When there is a change in the current user's token.
• When the following methods provided by FirebaseAuth.instance.currentUser are called:
• reload(), unlink(), updateEmail(), updatePassword(), updatePhoneNumber(), updateProfile()
final session = await user.multiFactor.getSession();
final auth = FirebaseAuth.instance; Firebase Authentication on Flutter
await auth.verifyPhoneNumber(
multiFactorSession: session, Enabling multi-factor authentication
phoneNumber: phoneController.text,
verificationCompleted: (_) {},
verificationFailed: (_) {},
codeSent: (String verificationId, int? resendToken) async {
// See `firebase_auth` example app for a method of retrieving user's sms code:
// https://github.com/firebase/flutterfire/blob/master/packages/firebase_auth/firebase_auth/example/lib/auth.dart#L591
final smsCode = await getSmsCodeFromUser(context);

if (smsCode != null) {
// Create a PhoneAuthCredential with the code
final credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: smsCode,
);

try {
await user.multiFactor.enroll(
PhoneMultiFactorGenerator.getAssertion(
credential,
),
);
} on FirebaseAuthException catch (e) {
print(e.message);
}
}
},
codeAutoRetrievalTimeout: (_) {},
);
Firebase Security Rules
Firebase Security Rules stand between your data and malicious users. You
can write simple or complex rules that protect your app's data to the level of
granularity that your specific app requires.

Firebase Security Rules leverage extensible, flexible configuration languages


to define what data your users can access for Realtime Database, Cloud
Firestore, and Cloud Storage.

Firebase Realtime Database Security Rules leverage JSON in rule definitions,


while Cloud Firestore Security Rules and Firebase Security Rules for Cloud
Storage leverage a unique language built to accommodate more complex
rules-specific structures.
Firebase Security Rules - Examples
Default rules: Locked mode
When you create a database or storage instance in the Firebase console, you
choose whether your Firebase Security Rules restrict access to your data
(Locked mode) or allow anyone access (Test mode). In Cloud Firestore and
Realtime Database, the default rules for Locked mode deny access to all
users. In Cloud Storage, only authenticated users can access the storage
buckets.

{
"rules": {
".read": false,
".write": false
}
}
Firebase Security Rules - Examples
For example, your app may want to make sure users can only read and write
their own data. In this scenario, you would want a match between the
auth.uid variable and the user ID on the requested data:

{
"rules": {
"users": {
"$userId": {
// grants write access to the owner of this user account
// whose uid must exactly match the key ($userId)
".write": "$userId === auth.uid"
}
}
}
}
Firebase – Real-Time Database
Structure Your Database

All Firebase Realtime Database data is stored as JSON objects. You can think of
the database as a cloud-hosted JSON tree. Unlike a SQL database, there are no
tables or records. When you add data to the JSON tree, it becomes a node in the
existing JSON structure with an associated key. You can provide your own keys,
such as user IDs or semantic names, or they can be provided for you using push().

{
"users": {
"alovelace": {
"name": "Ada Lovelace",
"contacts": { "ghopper": true },
},
"ghopper": { ... },
"eclarke": { ... }
}
}
Firebase – Real-Time Database
Basic write operations

For basic write operations, you can use set() to save data to a specified reference,
replacing any existing data at that path. You can set a reference to the following
types: String, boolean, int, double, Map, List.

For instance, you can add a user with set() as follows:

DatabaseReference ref =
FirebaseDatabase.instance.ref("users/123");

await ref.set({
"name": "John",
"age": 18,
"address": {
"line1": "100 Mountain View"
}
});
Firebase – Real-Time Database
Using set() in this way overwrites data at the specified location,
including any child nodes. However, you can still update a child without
rewriting the entire object. If you want to allow users to update their
profiles you could update the username as follows:

DatabaseReference ref =
FirebaseDatabase.instance.ref("users/123");

// Only update the name, leave the age and address!


await ref.update({
"age": 19,
});
Firebase – Real-Time Database
The update() method accepts a sub-path to nodes, allowing you to
update multiple nodes on the database at once:

DatabaseReference ref =
FirebaseDatabase.instance.ref("users");

await ref.update({
"123/age": 19,
"123/address/line1": "1 Mountain View",
});
Firebase – Real-Time Database
Basic Read data
You can use the DatabaseEvent to read the data at a given path, as it exists at the
time of the event. This event is triggered once when the listener is attached and
again every time the data, including any children, changes. The event has a
snapshot property containing all data at that location, including child data.
If there is no data, the snapshot's exists property will be false and its value
property will be null.

DatabaseReference starCountRef =

FirebaseDatabase.instance.ref('posts/$postId/s
tarCount');
starCountRef.onValue.listen((DatabaseEvent
event) {
final data = event.snapshot.value;
updateStarCount(data);
});
Firebase – Real-Time Database
Read data once with once()

In some cases you may want the value from the local cache to be returned
immediately, instead of checking for an updated value on the server. In those
cases you can use once() to get the data from the local disk cache immediately.

This is useful for data that only needs to be loaded once and isn't expected to
change frequently or require active listening. For instance, the blogging app in
the previous examples uses this method to load a user's profile when they begin
authoring a new post:

final event = await ref.once(DatabaseEventType.value);


final username = event.snapshot.value?.username ?? 'Anonymous';
• Firebase Cloud Messaging (FCM) is a cross-platform messaging
solution that lets you reliably send messages to clients.
Firebase
Cloud • Using FCM, you can notify a client app that new email or other
data is available to sync. You can send notification messages
Messaging to drive user re-engagement and retention. For use cases such
as instant messaging, a message can transfer a payload of up
to 4096 bytes to a client app.
Firebase Cloud Messaging

• Key capabilities

• Send notification messages or data


messages
• Send notification messages that are
displayed to your user. Or send data
messages and determine
completely what happens in your
application code.

• See Message types.


• Versatile message targeting
Distribute messages to your client
app in any of 3 ways—to single
devices, to groups of devices, or to
devices subscribed to topics.
Get to know Firebase for Flutter

https://firebase.google.com/codelabs/firebase-get-to-know-flutter#0
End of Module 6

You might also like