Skip to content

Fix: feat: firebase authentication guide #2 #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 67 additions & 10 deletions authentication/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,73 @@
# authentication
# Flutter Firebase Authentication Setup Guide

A new Flutter project.
This guide will walk you through the steps to configure Firebase Authentication in your Flutter project.

## Getting Started
## Step 1: Enable Firebase Authentication
1. Open the [Firebase Console](https://console.firebase.google.com/).
2. Select your project or create a new one.
3. In the Firebase Console, go to **Authentication** from the left-hand sidebar.
4. Click on the **Get Started** button.
5. Choose **Google** as a sign-in method and enable it.
6. Click **Save** to apply the changes.

This project is a starting point for a Flutter application.
Here are the two tables with images as requested:

A few resources to get you started if this is your first Flutter project:
### Table 1: Firebase Console Setup (Step 1)

- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
| Step | Image |
|------|-------|
| 1. Go to Firebase Console and choose Authentication | <img src="media/step1.png" height="300"> |
| 2. Click on "Get Started" to initialize the setup | ![](media/step1-2.png) |

For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
---

### Table 2: Google Authentication Configuration

| Step | Image |
|------|-------|
| 1. Enable Google Authentication in Firebase Console | ![](media/step2.png) |
| 2. Enable it and save the settings | ![](media/step2-2.png) ![](media/step2-3.png) |

## Step 2: Add Fingerprints for Android (Optional for Android apps)
If you're configuring Firebase for Android, you need to add the correct fingerprints for your app:

1. Open a terminal and run the following command to get your debug keystore fingerprint:

```bash
keytool -list -v -keystore C:\Users\<your-username>\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
```

2. Go to **Project Settings** in the Firebase Console.

3. Add the fingerprints you obtained from the command above.

### Table 3: Add Fingerprints for Android

| Action | Screenshot |
|--------|-----------|
| Go to Project Settings | ![](media/step3.png) |
| Obtain Fingerprints Using Command | ![](media/step3-1.png) |
| Add Fingerprints in Firebase | ![](media/step3-2.png) ![](media/step3-3.png)|


## Step 3: Add Firebase Configuration for Web (Optional for Web apps)

If you're working on a web app, you need to configure the Firebase settings in your web project:

1. Go to the Firebase Console and select your project.
2. In **Project Settings**, under the **General** tab, find your Firebase web configuration.
3. Follow the instructions to add the configuration to your `/web/index.html` file.

### Add Configure for Web

![](media/step4.png)

## Step 4: Run Flutterfire Configure

Once you’ve completed the setup in the Firebase Console, run the following command in your terminal to update your Flutter project with the latest Firebase configurations:

```bash
flutterfire configure
```

This will refresh your Flutter project to ensure the changes you made on the Firebase Console are reflected in your app.
3 changes: 3 additions & 0 deletions authentication/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
analyzer:
errors:
use_build_context_synchronously: ignore
include: package:flutter_lints/flutter.yaml

linter:
Expand Down
3 changes: 3 additions & 0 deletions authentication/android/app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
plugins {
id "com.android.application"
// START: FlutterFire Configuration
id 'com.google.gms.google-services'
// END: FlutterFire Configuration
id "kotlin-android"
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id "dev.flutter.flutter-gradle-plugin"
Expand Down
3 changes: 3 additions & 0 deletions authentication/android/settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ pluginManagement {
plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "8.1.0" apply false
// START: FlutterFire Configuration
id "com.google.gms.google-services" version "4.3.15" apply false
// END: FlutterFire Configuration
id "org.jetbrains.kotlin.android" version "1.8.22" apply false
}

Expand Down
122 changes: 9 additions & 113 deletions authentication/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,125 +1,21 @@
import 'package:authentication/firebase_options.dart';
import 'package:authentication/pages/login/login.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() {
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();

await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
return MaterialApp(home: Login());
}
}
91 changes: 91 additions & 0 deletions authentication/lib/pages/home/home.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import 'package:authentication/services/auth_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Home extends StatelessWidget {
const Home({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Flutter Firebase Authentication",
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.amber[900],
elevation: 0,
toolbarHeight: 80,
),
backgroundColor: Colors.white,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildWelcomeText(),
const SizedBox(height: 20),
_buildUserEmail(),
const SizedBox(height: 40),
_buildLogoutButton(context),
],
),
),
),
);
}

// Welcome text for the user
Widget _buildWelcomeText() {
return const Text(
'Welcome to Flutter Firebase Authentication Example',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 24,
),
);
}

// Display current user's email
Widget _buildUserEmail() {
return Text(
FirebaseAuth.instance.currentUser?.email ?? 'No email found',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 18,
),
);
}

// Logout button with an attractive design
Widget _buildLogoutButton(BuildContext context) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.amber[900],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
minimumSize: const Size(double.infinity, 60),
elevation: 5,
shadowColor: Colors.blue.withOpacity(0.3),
),
onPressed: () async {
await AuthService().signout(context: context);
},
child: const Text(
"Sign Out",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
);
}
}
Loading