Skip to content

From this repository, you can see how to make a Firebase Authentication to your Flutter app.

Notifications You must be signed in to change notification settings

orosiferenc3/Flutter_Firebase_Auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Flutter Firebase Authentication

In this project I show you how to make a Firebase Authentication. If you want to use this code you have to make your own Firebase project and you should copy your google-services.json to android/app folder.

Sign In Page

signin

Sign Up Page

signup

Home Page

home

android/app

You need to copy the google-services.json to android/app folder

pubspec.yaml

You need these packages in pubspec.yalm

dependencies:
  flutter:
    sdk: flutter
  firebase_core: "^0.5.2"
  firebase_auth: "^0.18.3"

android/build.gradle

In your android/build.gradle file you need these codes:

buildscript {
    repositories {
        google() // Google's Maven repository
    }

    dependencies {
        classpath 'com.google.gms:google-services:4.3.4' // Google Services plugin
    }
}
allprojects {
    repositories {
        google() // Google's Maven repository
    }
}

android/app/build.gradle

Your android/app/build.gradle file need to contains the following codes:

apply plugin: 'com.google.gms.google-services' // Google Services plugin
dependencies {
    implementation platform('com.google.firebase:firebase-bom:26.1.0')
    implementation 'com.google.firebase:firebase-auth'
}

main.dart

In the main.dart file you need this import:

import 'package:firebase_core/firebase_core.dart';

void main should look like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

You need to set your homepage as home and you need to make routes which are provides the routes between the pages.

home: HomePage(),
routes: <String, WidgetBuilder>{
   "/SignInPage": (BuildContext context) => SignInPage(),
   "/SignUpPage": (BuildContext context) => SignUpPage(),
},

homePage.dart

In the homePage.dart file you need this import:

import 'package:firebase_auth/firebase_auth.dart';

You need three variable:

final FirebaseAuth _auth = FirebaseAuth.instance;
User user;
bool isSignedIn = false;

You need a check status method, a get info method and a sign out method.

checkSignInStatus() async {
    _auth.authStateChanges().listen((User user) {
      if (user == null) {
        Navigator.pushReplacementNamed(context, "/SignInPage");
      }
    });
  }

  getInfo() async {
    _auth.authStateChanges().listen((User user) {
      if (this.user != null) {
        setState(() {
          this.user = user;
          this.isSignedIn = true;
        });
      }
    });
  }

  signOut() {
    _auth.signOut();
    print('SignOut: Sign out was successful.');
  }

You have to call the async task in the initState()

@override
void initState() {
  super.initState();
  this.checkSignInStatus();
  this.getInfo();
}

If you press the button you will sign out.

RaisedButton(
  onPressed: () {
    signOut();
  },
  child: Center(
    child: Text('Sign-out'),
  ),
),

signInPage.dart

In the signInPage.dart file you need this import:

import 'package:firebase_auth/firebase_auth.dart';

You need three variable:

final FirebaseAuth _auth = FirebaseAuth.instance;
final username = TextEditingController();
final password = TextEditingController();

You need a check current user method, a sign in method and a tosignup method.

  checkCurrentUser() async {
    _auth.authStateChanges().listen((User user) async {
      if (user != null) {
        Navigator.pushReplacementNamed(context, "/");
      }
    });
  }

  void signIn() async {
    try {
      if (username.text != "" && password.text != "") {
        UserCredential userCredential = await _auth.signInWithEmailAndPassword(
            email: username.text, password: password.text);
        print('SignIn: Sign in was successful.');
        print(userCredential);
      } else {
        print('SignIn: Username or password is missing.');
      }
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('SignIn: No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('SignIn: Wrong password provided for that user.');
      }
    }
  }

  toSignUp() async {
    Navigator.pushReplacementNamed(context, "/SignUpPage");
  }

You have to call the async task in the initState() except the signin because it will cause a warning or error.

@override
void initState() {
  super.initState();
  this.checkCurrentUser();
}

You have to dispose the controllers value.

@override
void dispose() {
  super.dispose();
  username.dispose();
  password.dispose();
}

A textfield should look like this. The important thing is the controller.

TextField(
  controller: username,
  obscureText: false,
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    hintText: 'E-mail/Username',
  ),
),

If you press the button the sign in method will be executed.

RaisedButton(
  onPressed: () {
    signIn();
  },
  child: Center(
    child: Text('Sign-in'),
  ),
),

I use a gesture detector to navigate the user to the sign up page.

GestureDetector(
  onTap: () {
    toSignUp();
  },
  child: Text(
    "Sign Up!",
    style: TextStyle(color: Colors.blue),
  ),
),

signUpPage.dart

In the signUpPage.dart file you need this import:

import 'package:firebase_auth/firebase_auth.dart';

You need three variable:

final FirebaseAuth _auth = FirebaseAuth.instance;
final username = TextEditingController();
final password = TextEditingController();

You need a check authentication method, a sign up method and a tosignin method.

  checkAuthentication() async {
    _auth.authStateChanges().listen((User user) {
      if (user != null) {
        Navigator.pushReplacementNamed(context, "/");
      }
    });
  }

  toSignIn() async {
    Navigator.pushReplacementNamed(context, "/SignInPage");
  }

  void signUp() async {
    try {
      UserCredential userCredential =
          await _auth.createUserWithEmailAndPassword(
              email: username.text, password: password.text);
      print(userCredential);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        print('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
      }
    } catch (e) {
      print(e);
    }
  }

You have to call the async task in the initState() except the signin because it will cause a warning or error.

@override
void initState() {
  super.initState();
  this.checkAuthentication();
}

You have to dispose the controllers value.

@override
void dispose() {
  super.dispose();
  username.dispose();
  password.dispose();
}

A textfield should look like this. The important thing is the controller.

TextField(
  controller: username,
  obscureText: false,
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    hintText: 'E-mail/Username',
  ),
),

If you press the button the sign up method will be executed.

RaisedButton(
  onPressed: () {
    signUp();
  },
  child: Center(
    child: Text('Sign-Up'),
  ),
),

I use a gesture detector to navigate the user to the sign in page.

GestureDetector(
  onTap: () {
    toSignIn();
  },
  child: Text(
    "Sign In!",
    style: TextStyle(color: Colors.blue),
  ),
),

About

From this repository, you can see how to make a Firebase Authentication to your Flutter app.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published