06-Module 6
06-Module 6
06-Module 6
Mobile Programming
MODULE 6:
CLOUD SERVICES: USING FIREBASE IN FLUTTER
Add Firebase to your Flutter app
• Step 1: Install the required command line tools
– firebase login
• 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,
);
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
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.
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.
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
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.
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.
{
"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.
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");
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:
• Key capabilities
https://firebase.google.com/codelabs/firebase-get-to-know-flutter#0
End of Module 6