arrow_back

Flutter Web and Firebase Authentication

Join Sign in

Flutter Web and Firebase Authentication

1 hour 1 Credit

GSP888

Google Cloud self-paced labs logo

Overview

Flutter is Google's UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source.

In this lab, you will create a Firebase Meetup application. The application will demonstrate how to use Firebase Web authentication in a Flutter application.

The Firebase Meetup application user interface

What you'll learn

  • How to write a Flutter app that looks natural on iOS, Android, and the web

  • Basic structure of a Flutter app

  • The basics of Firebase

Prerequisites

Based on the content, it is recommended to have some familiarity with:

  • Flutter

  • Dart

  • Firebase Web Authentication

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

Task 1. Open the frontend service

In this lab, we will use a custom editor that includes the Flutter and Dart extensions. The lab environment is preprovisioned.

Note: Code Server Editor

  • Based on VS Code
  • Supports Extensions
  1. Copy the IDE address from the lab details panel:

lab details panel displaying the username, password, IDE and Live Server details

  1. Paste the IP address into a Browser.

Task 2. Clone the code repository

The lab has pre-existing code located on GitHub. In this section clone the repository and prepare the environment to use the code.

  1. Select the Source Control button (highlighted in white):

The Source Control button is selected and the Source Control page is displayed

  1. Click the Clone Repository button.

  2. Enter the repository https://github.com/flutter/codelabs.git:

The Search field populated with repository URL

  1. Click the Clone from URL link.

  2. Set the destination folder /home/ide-dev and press the OK button:

The destination folder path alongside the OK button.

  1. Dismiss the open the cloned repository message - press the X:

A pop-up displaying the question, 'Would you like to open the cloned repository?'

Note: Cloned Repositories

  • Where a repository contains multiple Flutter/Dart applications opening a specific folder can be easier to manage.
  • To see the full folder contents of the cloned repository, use the above option.

The code has now been cloned into the editor. In the next section access the source code and explore the Flutter application.

Task 3. Import the starter app

In this section access the Flutter application for Firebase Web authentication.

Note: The directory structure under `flutter-codelabs/firebase-get-to-know-flutter` contains a series of snapshots. Reference these snapshots during the lab to understand how the code should look once the changes have been made.
  1. Select the Explorer button (highlighted in white):

The selected Explorer button and Explorer page is displayed

  1. Open the folder:

/home/ide-dev/codelabs/firebase-get-to-know-flutter/step_02
  1. Click on pubspec.yaml.

  2. Click the Get Packages icon (downward facing arrow):

Toolbar displaying the Get Packages icon

  1. Click on the lib/main.dart.

  2. Click on the application menu (Top Left three horizontal lines):

The expanded application menu

  1. Click Terminal.

  2. Click on the New Terminal option.

  3. Ensure terminal directory to is set to correct working directory e.g.:

codelabs/firebase-get-to-know-flutter/step_02

The editor has now been updated with the code and terminal window. Before coding, in the next section explore the Flutter code to improve understanding.

Task 4. Exploring the Flutter code

The application code is organized over multiple directories. This split of functionality is designed to make it easier to work on, by grouping code by functionality:

File

Description

lib/main.dart

This file contains the main entry point and the application widget.

lib/src/widgets.dart

This file contains a handful of widgets to help standardise the styling of the application. These are used to compose the screen of the starter app.

lib/src/authentication.dart

This file contains a partial implementation of FirebaseUI Auth with a set of widgets to create a login user experience for Firebase email based authentication. These widgets for the auth flow are not yet used in the starter app, but you will wire them in soon.

web/index.html

This file contains the web configuration for the application. The Firebase web authentication will be added to this file.

The application will utilise helper widgets from lib/src/widgets.dart in the form of Header, Paragraph and IconAndDetail.

Note: The application will utilise helper widgets from lib/src/widgets.dart in the form of Header, Paragraph and IconAndDetail. These widgets reduce clutter in the page layout described in HomePage by eliminating duplicated code. This has the additional benefit of enabling a consistent look and feel.

Take a moment to explore the code. In the next section, run the template application and access the web application.

Task 5. Running the sample Flutter code

In this section the Flutter Web application will be run from the command line.

Note: Web server

  • Building a Web application
  • Flutter application will be run in the browser
  • Tell Flutter to use the browser on a specific port

In the Explorer view of the IDE, update the sdk: attribute in the pubspec.yaml file to the following:

sdk: '>=2.18.0 <3.0.0'
  1. Enter the following command in the terminal:

fwr
  1. The running web server should look similar to below:

The Command Line Terminal tab displaying the running web server details

  1. Copy the Live Server and paste into a new Browser tab.

  2. The application should be similar to the image shown below:

The Firebase Meetup page displaying the date, location, and description of what everyone will be doing

The application displays the details of a Firebase Meetup. In the next section, learn how to add a Firebase backend.

Task 6. Adding a Firebase backend

To get started with Firebase, you'll need to create and set up a Firebase project.

  1. Use a new Incognito Browser tab to sign in to the Firebase console.

  2. At the Sign In prompt - use the Username + Password from the Qwiklabs panel.

  3. From the Firebase console, click Add project.

  4. Select the Qwiklabs project from the drop down menu e.g.:

The Enter you project name dropdown menu displaying the Qwiklabs project info

  1. Accept Firebase terms and click Continue.
  2. Confirm Firebase billing plan as Pay as you go by clicking Confirm plan.
  3. Click Continue for step 2.
  4. Deselect Enable Google Analytics for this project for the project as we will not be using this.
  5. Click the Add Firebase.
  6. Click Continue to finalise Firebase project creation.

Firebase has now been configured for your project. In the next section we will be configuring Firebase Web for our Flutter application.

Task 7. Firebase for the Web

Firebase provides multiple mobile options i.e. iOS, Android, Web and Unity. In this section setup Firebase to use a web application.

  1. Click the Web option i.e. </>:

The Firebase Get started page, displaying additional app options

  1. Firebase needs some more information to configure Web access:

The Add Firebase to your webb app dialog box displaying the Register app step section details

  1. Enter an App nickname as:

Get to Know Firebase for Flutter on the Web
  1. Leave the Firebase Hosting checkbox unticked.

  2. Click Register app. Select the script radio option for the Firebase Config options presented.

  3. At this point the firebaseConfig will be displayed. Copy the Firebase SDK script. An example Firebase SDK script is shown below:

<!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script> <!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries --> <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "AIzaSyBtDhrHFPzAuisb1OUoOCtH5qFQfJQj5P8", authDomain: "qwiklabs-gcp-02-275e7ff68e9b.firebaseapp.com", projectId: "qwiklabs-gcp-02-275e7ff68e9b", storageBucket: "qwiklabs-gcp-02-275e7ff68e9b.appspot.com", messagingSenderId: "747684473419", appId: "1:747684473419:web:bbdaccbe986279644d3bce" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); </script> Note: Get to know Firebase for Flutter on the web

The existing app configuration will be accessible via the Project Overview:
  1. Select the app created to see the details specified.
  2. Click the cog and scroll down the page to review the SDK configuration script.
  1. Click Continue to console to continue to the next screen.

At this point the Firebase app has been configured. However we have not told it how it will be used. Add an Authentication configuration based on a user sign-in with email.

  1. Click Authentication.
  2. Click Get Started.
  3. Enable the Email/Password option from the list of Sign-in providers.
  4. Click Save.

The backend has now been configured to enable Firebase to be used for Web authentication using email. In the next section learn how to update the application to utilise Firebase Authentication.

Task 8. Adding Firebase Authentication (RSVP)

In this section update the Flutter application and add an RSVP button that registers people using Firebase Authentication.

Note: Web authentication

For Android native, iOS native, and Web there are pre-built FirebaseUI Auth packages, but for Flutter you will need to build this capability.
  1. Go back to the editor and find the web folder and expand it to reveal an index.html file.

  2. Click on the index.html file to open it in the editor.

  3. Append the html body section with the Firebase script shown below (directly below the body tag). Make sure you only include the section between the "Add from here" and "to here" comments in the code snippet below.

<body> <!-- Add from here --> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script> <script> // Your web app's Firebase configuration var firebaseConfig = { // Replace this with your firebaseConfig }; // Initialize Firebase firebase.initializeApp(firebaseConfig); </script> <!-- to here. --> <script> if ('serviceWorker' in navigator) { window.addEventListener('flutter-first-frame', function () { navigator.serviceWorker.register('flutter_service_worker.js'); }); } </script> <script src="main.dart.js" type="application/javascript"></script> </body>
  1. Copy the firebaseConfig from the SDK setup and configuration in Firebase e.g.:

apiKey: "AIzaSyDjql-DdKOfc9vJ4JC9MV7kLwRHdwMuy2E", authDomain: "qwiklabs-gcp-03-f9368fcccd45.firebaseapp.com", projectId: "qwiklabs-gcp-03-f9368fcccd45", storageBucket: "qwiklabs-gcp-03-f9368fcccd45.appspot.com", messagingSenderId: "758615644147", appId: "1:758615644147:web:47f3d57ac3ecc7e2056486"
  1. Replace the firebaseConfig section in index.html e.g.:

var firebaseConfig = { apiKey: "AIzaSyDjql-DdKOfc9vJ4JC9MV7kLwRHdwMuy2E", authDomain: "qwiklabs-gcp-03-f9368fcccd45.firebaseapp.com", projectId: "qwiklabs-gcp-03-f9368fcccd45", storageBucket: "qwiklabs-gcp-03-f9368fcccd45.appspot.com", messagingSenderId: "758615644147", appId: "1:758615644147:web:47f3d57ac3ecc7e2056486" };
  1. The updated body section should now look similar to below:

<body> <!-- Add from here --> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script> <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "AIzaSyDjql-DdKOfc9vJ4JC9MV7kLwRHdwMuy2E", authDomain: "qwiklabs-gcp-03-f9368fcccd45.firebaseapp.com", projectId: "qwiklabs-gcp-03-f9368fcccd45", storageBucket: "qwiklabs-gcp-03-f9368fcccd45.appspot.com", messagingSenderId: "758615644147", appId: "1:758615644147:web:47f3d57ac3ecc7e2056486" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); </script> <!-- to here. --> <!-- This script installs service_worker.js to provide PWA functionality to application. For more information, see: https://developers.google.com/web/fundamentals/primers/service-workers --> <script> if ('serviceWorker' in navigator) { window.addEventListener('flutter-first-frame', function () { navigator.serviceWorker.register('flutter_service_worker.js'); }); } </script> <script> window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, } }).then(function(engineInitializer) { return engineInitializer.initializeEngine(); }).then(function(appRunner) { return appRunner.runApp(); }); }); </script> </body>

That completes configuring the Flutter app for the Web. To learn more review the Web Installation documentation.

The Flutter project includes a set of widgets that implements the user interface for most of the authentication flow.

  1. Add the imports marked new to lib/main.dart:

import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'src/widgets.dart'; import 'dart:async'; // new import 'package:firebase_auth/firebase_auth.dart' // new hide EmailAuthProvider, PhoneAuthProvider; // new import 'package:firebase_core/firebase_core.dart'; // new import 'package:firebase_ui_auth/firebase_ui_auth.dart'; // new import 'package:provider/provider.dart'; // new import 'firebase_options.dart'; // new import 'src/authentication.dart'; // new Note: The import lines introduce Firebase Core and Auth, as well as the provider package which is used to make the application state object available through the widget tree, and includes the authentication widgets from `firebase_ui_auth`.

Further information on Flutter packages can be found on the pub.dev website.

Run the following commands to install imported packages. You can start another terminal window in the IDE by clicking the + icon to open a new terminal (near the bash logo of the terminal view):

dart pub global activate flutterfire_cli flutter pub add provider firebase_auth firebase_core cloud_firestore firebase_ui_auth flutterfire configure

After running flutterfire configure you may be prompted to select your project and platforms to utilize. Press Enter at all of the prompts to continue.

  1. Add the following code at the end of the lib/main.dart file:

class ApplicationState extends ChangeNotifier { ApplicationState() { init(); } bool _loggedIn = false; bool get loggedIn => _loggedIn; Future<void> init() async { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform); FirebaseUIAuth.configureProviders([ EmailAuthProvider(), ]); FirebaseAuth.instance.userChanges().listen((user) { if (user != null) { _loggedIn = true; } else { _loggedIn = false; } notifyListeners(); }); } } Note: The code isn't a complete implementation of the FirebaseUI Auth flow, as it does not handle the case of a user with an existing account who is having trouble logging in. Implementing this additional capability is left as an exercise to the motivated reader.

We are using a provider here to communicate to the app that state of a users login status, nothing more. To login a user, we are going to use the UIs provided by firebase_ui_auth which is a great way to quickly bootstrap login screens for your applications.

Task 9. Integrating authentication validation

In this section wire the application state into the app initialization and add the authentication flow into HomePage. Update the main entry point to integrate application state via the provider package:

  1. Replace the main method in lib/main.dart:

void main() { // Modify from here WidgetsFlutterBinding.ensureInitialized(); runApp(ChangeNotifierProvider( create: (context) => ApplicationState(), builder: ((context, child) => const App()), )); // to here. }
  1. Since you are using FirebaseUI for Flutter, you will update your app to handle navigating to different screens that FirebaseUI provides for you. To do this, add the following code snippet to the MaterialApp class' properties in the lib/main.dart file:

//Start adding here initialRoute: '/home', routes: { '/home': (context) { return const HomePage(); }, '/sign-in': ((context) { return SignInScreen( actions: [ ForgotPasswordAction(((context, email) { Navigator.of(context) .pushNamed('/forgot-password', arguments: {'email': email}); })), AuthStateChangeAction(((context, state) { if (state is SignedIn || state is UserCreated) { var user = (state is SignedIn) ? state.user : (state as UserCreated).credential.user; if (user == null) { return; } if (state is UserCreated) { user.updateDisplayName(user.email!.split('@')[0]); } if (!user.emailVerified) { user.sendEmailVerification(); const snackBar = SnackBar( content: Text( 'Please check your email to verify your email address')); ScaffoldMessenger.of(context).showSnackBar(snackBar); } Navigator.of(context).pushReplacementNamed('/home'); } })), ], ); }), '/forgot-password': ((context) { final arguments = ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?; return ForgotPasswordScreen( email: arguments?['email'] as String, headerMaxExtent: 200, ); }), '/profile': ((context) { return ProfileScreen( providers: [], actions: [ SignedOutAction( ((context) { Navigator.of(context).pushReplacementNamed('/home'); }), ), ], ); }) }, // end adding here
  1. Replace the HomePage build method in lib/main.dart:

class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Consumer<ApplicationState>( builder: (context, appState, child) => Scaffold( appBar: AppBar( title: const Text('Firebase Meetup'), ), body: ListView( children: <Widget>[ Image.asset('assets/codelab.png'), const SizedBox(height: 8), const IconAndDetail(Icons.calendar_today, 'October 30'), const IconAndDetail(Icons.location_city, 'San Francisco'), // Add from here Consumer<ApplicationState>( builder: (context, appState, _) => AuthFunc( loggedIn: appState.loggedIn, signOut: () { FirebaseAuth.instance.signOut(); }), ), // to here const Divider( height: 8, thickness: 1, indent: 8, endIndent: 8, color: Colors.grey, ), const Header("What we'll be doing"), const Paragraph( 'Join us for a day full of Firebase Workshops and Pizza!', ), ], ), )); } }

At this point, check the application for errors before proceeding on to the next section!

Task 10. Running the sample Flutter code

In this section run the Flutter Web application from the command line.

Note: The running web server will need to be stopped to take account of the changes made to the application.
  • Stop the active web server.
  • Restart the web server with the following command: fwr
  1. Stop the active web server
  2. Restart the web server to take account of application changes.
  3. The application should be similar to the image shown below:

The Firebase Meetup page displaying the date, locaton, and itinerary, as well as the RSVP button

Note the addition of the RSVP button. In the next section we will check the associated authentication functionality.

Task 11. Testing the authentication flow

In this section start to test the application updates together with the authentication flow. At the start of the authentication flow, the user can tap on the RSVP button, to initiate the email form.

Note: The application confirms if the user is already registered.

  • Registered: the user is prompted for a password,
  • Not registered: the user is prompted for account details via the registration form.

Error handling to ensure short passwords (less than six characters) are not used.

  1. Click the RSVP button then click Register on the login form.
  2. Enter an email address e.g. [angela@gmail.com](mailto:angela@gmail.com).
  3. Enter a password for the account e.g. Password01
  4. Click the Save button:

The Firebase Meetup Create account page, displaying the populated email address, name, and passwrod fields, as well as Save and Cancel buttons

  1. In Firebase Authentication, verify the user has been saved:

The Users tab on the Authentication page, displaying the user email address, date created, date signed in, and User UID details

We now have a user registered on the system. Lets try that workflow again to access that user.

  1. Click the RSVP button.
  2. Enter an email address e.g. [angela@gmail.com](mailto:angela@gmail.com).
  3. Enter a password for the account e.g. Password01.
  4. Click the SIGN IN button.

The Firebase Meetup page displaying the date, locaton, and itinerary, as well as the Logout button

Great work. The meetup information for the registered user account is now able to address individual users.

Click Check my progress to verify the objective. Assess my progress

Congratulations

You have successfully completed the lab and demonstrated your knowledge of Flutter. Over the course of this lab, you have performed the following tasks:

  • Developed a Firebase Flutter web application

  • Learned to use hot reload feature

  • Implemented Firebase Web authentication

  • Tested code updates in the web device

Finish your quest

This self-paced lab is part of the Flutter Development quest. A quest is a series of related labs that form a learning path. Completing this Quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Flutter Development or any quest that contains this lab and get immediate completion credit. See the Google Cloud Skills Boost catalog to see all available quests.

Take your next lab

Continue your quest with Dart Functions Framework, or check out these suggestions:

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated October 14, 2022

Lab Last Tested April 8, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.