Login and Registration in Flutter using Firebase

Login and Registration in Flutter using Firebase

What we will build in this article?

In this article, we are going to build a simple login and registration page with the help of a Firebase Database. Firebase Database is google’s official platform for mobile and web application development. We will use a firebase for authentication of the user’s data.

Steps to follow

First of all, create a new project and make your project compatible with Androidx.

If your project is compatible with Androidx then skip this step and move forward.

How to Migrate Flutter project to Compatible with Androidx?

For migrating an existing flutter project to androidx we have two methods.

one is a very simple method is that open your existing flutter project in Android Studio and from the menu select edit and choose Migrate to AndroidX, which converts all project with compatible to Androidx with a single click.

second is migrate manually with copy and paste the Androidx compatible code to the Gradle files and properties.

What will be the requirement for this tutorial?

For this tutorial, we have the requirement of a Gmail account for creating Firebase Console, where we will use authentication of the user. and we are going to create the following screens for our project.

  • main.dart
  • Signup.dart
  • Login.dart
  • HomePage.dart

Main.dart

Main.dart file is the main file execute at the run time of the project.

Signup.dart

Signup.dart¬† file will use for taking input information from the user’s and to store data into the database.

Login.dart

Login.dart file will use for taking input from the user and proceed these data to firebase and return the information that the provided information is matched or not.

If the provided information got matched then the user will log in successfully otherwise firebase return error according to the error. and

HomePage.dart

HomePage.dart file will be used for the main page which will display information to the user after successfully logged in or registered.

Flutter Google SignIn Firebase Authentication

Let’s start the project

Create a new flutter project by running command flutter create authentication

after the successful creation of the project file open folder in vs code and locate the folder lib and inside lib folder, you will get a main.dart file. replace all the demo code of main.dart file with this main.dart.

main.dart

import 'package:contact_app/MainPage.dart';
import 'package:flutter/material.dart';
import 'Screens/HomePage.dart';
import 'SigninPage.dart';
import 'SignupPage.dart';

void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Login Page',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MainPage(),
      routes: <String, WidgetBuilder>{
        "/SigninPage": (BuildContext context) => SigninPage(),
        "/SignupPage": (BuildContext context) => SignupPage(),
      },
    );
  }
}

Here we have defined our SigninPage and SighupPage using routes.
and called the main function as MainPage(). This page will initially contain some information that will be displayed to the user after login or registration.
Now create a Page named it MainPage.dart

MainPage.dart

import 'package:contact_app/Profile.dart';
import 'package:contact_app/Screens/HomePage.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}

class _MainPageState extends State {
//Firebase Auth and .instance is use to directly contact to firebase
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user;
bool isSignedIn = false;

// checkAuthentication method is continuasly check wether the user is loged in or not

checkAuthentication() async {
_auth.onAuthStateChanged.listen((user){
if (user == null) {
Navigator.pushReplacementNamed(context, "/SigninPage");
}
});
}
// if user is loged in then it will show the details
getUser() async {
FirebaseUser firebaseUser = await _auth.currentUser();
await firebaseUser?.reload();
firebaseUser = await _auth.currentUser();

if (firebaseUser != null) {
setState((){
this.user = firebaseUser;
this.isSignedIn = true;
});
}
}
// sign out from the login
signOut() async {
_auth.signOut();
}
@override
void initState() {
super.initState();
this.checkAuthentication();
this.getUser();
}

@override
Widget build(BuildContext context) {
return
WillPopScope(
onWillPop: (){
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("Warning"),
content: Text("Are you sure want to exit?"),
actions: [
FlatButton(
child: Text("No"),
onPressed: (){
Navigator.of(context).pop(false);
},
),
FlatButton(
child: Text("Yes"),
onPressed: (){
Navigator.of(context).pop(true);
},
)
],
)
);
},
child: Scaffold(
appBar: AppBar(
title: Text("HomePage"),
),
drawer: Drawer(
child: ListView(

children: [
UserAccountsDrawerHeader(
currentAccountPicture: Icon(Icons.camera,size: 40,),
accountName: Text("Manali Village",style: TextStyle(fontSize: 22.0,fontWeight: FontWeight.bold),),
accountEmail: Text("manali@gmail.com",style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.bold),),
),

ListTile(
contentPadding: EdgeInsets.fromLTRB(20, 5, 50, 0),
title: Text("Profile",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
trailing: Icon(Icons.home),
onTap: (){
// assign the address of routes where want to go
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context) =>new ProfilePage(),
));
},
),
Divider(
color: Colors.black,
height: 10,
),
ListTile(
contentPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
title: Text("Contact us",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
trailing: Icon(Icons.contacts),
onTap: (){
// assign the address of routes where want to go
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context) =>new Contact(),
));
},
),
Divider(
color: Colors.black,
height: 10,
),
ListTile(
contentPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
title: Text("About Us",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
trailing: Icon(Icons.confirmation_number),
onTap: (){
// assign the address of routes where want to go
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context) =>new AboutUs(),
));
},
),
Divider(
color: Colors.black,
height: 10,
)
],
),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.home ,size: 45.0, color: Colors.orange,),
RaisedButton(
child: Text('Open'),
onPressed:(){
Navigator.push(context, MaterialPageRoute(builder: (context)=>HomePage()));
}
)
],
),
)
)
),
);
}
}

import 'package:contact_app/Profile.dart';
import 'package:contact_app/Screens/HomePage.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State {
  //Firebase Auth and .instance is use to directly contact to firebase
  final FirebaseAuth _auth = FirebaseAuth.instance;
  FirebaseUser user;
  bool isSignedIn = false;

// checkAuthentication method is continuasly check wether the user is loged in or not

  checkAuthentication() async {
    _auth.onAuthStateChanged.listen((user){
      if (user == null) {
        Navigator.pushReplacementNamed(context, "/SigninPage");
      }
    });
  }
// if user is loged in then it will show the details
  getUser() async {
    FirebaseUser firebaseUser = await _auth.currentUser();
    await firebaseUser?.reload();
    firebaseUser = await _auth.currentUser();

    if (firebaseUser != null) {
      setState((){
        this.user = firebaseUser;
        this.isSignedIn = true;
      });
    }
  }
// sign out from the login
  signOut() async {
    _auth.signOut();
  }
  @override
  void initState() {
    super.initState();
    this.checkAuthentication();
    this.getUser();
  }

  @override
  Widget build(BuildContext context) {
    return 
        WillPopScope(
                onWillPop: (){
                  return showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: Text("Warning"),
                    content: Text("Are you sure want to exit?"),
                    actions: [
                      FlatButton(
                        child: Text("No"),
                        onPressed: (){
                          Navigator.of(context).pop(false);
                        },
                      ),
                      FlatButton(
                        child: Text("Yes"),
                        onPressed: (){
                          Navigator.of(context).pop(true);
                        },
                      )
                    ],
                    )
                  );
                },
                child: Scaffold(
                  appBar: AppBar(
              title: Text("HomePage"),
            ),
            drawer: Drawer(
              child: ListView(
                
                children: [
                  UserAccountsDrawerHeader(
                    currentAccountPicture: Icon(Icons.camera,size: 40,),
                    accountName: Text("Manali Village",style: TextStyle(fontSize: 22.0,fontWeight: FontWeight.bold),),
                    accountEmail: Text("manali@gmail.com",style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.bold),),
                  ),
               
                  ListTile(
                    contentPadding: EdgeInsets.fromLTRB(20, 5, 50, 0),
                    title: Text("Profile",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
                    trailing: Icon(Icons.home),
                    onTap: (){
                      // assign the address of routes where want to go
                      Navigator.of(context).push(new MaterialPageRoute(
                        builder: (BuildContext context) =>new ProfilePage(),
                      ));
                    },
                  ),
                  Divider(
                    color: Colors.black,
                    height: 10,
                  ),
                  ListTile(
                    contentPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
                    title: Text("Contact us",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
                    trailing: Icon(Icons.contacts),
                    onTap: (){
                      // assign the address of routes where want to go
                      Navigator.of(context).push(new MaterialPageRoute(
                        builder: (BuildContext context) =>new Contact(),
                      ));
                    },
                  ),
                  Divider(
                    color: Colors.black,
                    height: 10,
                  ),
                  ListTile(
                    contentPadding: EdgeInsets.fromLTRB(20, 0, 50, 0),
                    title: Text("About Us",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),),
                    trailing: Icon(Icons.confirmation_number),
                    onTap: (){
                      // assign the address of routes where want to go
                      Navigator.of(context).push(new MaterialPageRoute(
                        builder: (BuildContext context) =>new AboutUs(),
                      ));
                    },
                  ),
                  Divider(
                    color: Colors.black,
                    height: 10,
                  )
                ],
              ),
            ),
            body: Container(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.home ,size: 45.0, color: Colors.orange,),
                    RaisedButton(
                      child: Text('Open'),
                      onPressed:(){
                        Navigator.push(context, MaterialPageRoute(builder: (context)=>HomePage()));
                      }
                    )
                  ],
                ),
                )
            )
                ),
              );
  }
}

SigninPage.dart

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class SigninPage extends StatefulWidget {
  @override
  _SigninPageState createState() => _SigninPageState();
}

class _SigninPageState extends State {

  //Firebase Auth and .instance is use to directly contact to firebase

    final FirebaseAuth _auth = FirebaseAuth.instance;
    // using for grab the form key for our form data
    final GlobalKey _formKey = GlobalKey();

    //there are only 2 input in sigin page so declare here
    String _email, _password;
// checkAuthentication method is continuasly check wether the user is loged in or not
    checkAuthentication() async {
      _auth.onAuthStateChanged.listen((user) async {
        if (user !=null) {
          Navigator.pushReplacementNamed(context, "/");
          
        }

      });
    }
    //if user is loged out then signup page will open.
    navigateToSignupScreen(){
      Navigator.pushReplacementNamed(context, "/SignupPage");
    }
// when the application will lauch then it will go for checkAuthentication
    @override
    void initState() {
    super.initState();
   this.checkAuthentication();
  }

//method for sign in . it will check the current status of formkey and validate and save them.
  void signin() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();

  // wrapping the firebase call to signInWithEmailAndPassword
  //and in case of any error catch method will work
        try {
        AuthResult user = (await _auth.signInWithEmailAndPassword(
          email: _email, password: _password));
      } catch (e) {
          showError(e.message);
      } 
    }
  }
// Show message for any kind of error occured in application
  showError(String errorMessage){
    showDialog(
      context: context,
      builder: (BuildContext context){
        return AlertDialog(
          title: Text('Error'),
          content: Text(errorMessage),
          actions: [
            FlatButton(
              child: Text("OK"),
              onPressed: (){
                Navigator.of(context).pop();
              },
            )
          ],
        );
      }
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Signin Page'),
      ),
      body: Container(
        child: Center(
          child: ListView(
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(10.0, 50.0, 10.0, 50.0),
                child: Image(
                  image: AssetImage("assets/logo.png"),
                  width: 100,
                  height: 100,
                ),
              ),
              Container(
                padding: EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    children: [
                      //email
                      Container(
                        padding: EdgeInsets.all(10.0),
                        child: TextFormField(
                          validator: (input){
                            if (input.isEmpty) {
                              return 'Provide an email';
                            }
                          },
                          decoration: InputDecoration(
                            labelText: 'Email',
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0)
                            )
                          ),
                          onSaved: (input) => _email = input,
                        ),
                      ),
                      //password
                      Container(
                        padding: EdgeInsets.all(10.0),
                        child: TextFormField(
                          validator: (input){
                            if (input.length<6) { return 'Password should be atleast 6 char.'; } }, decoration: InputDecoration( labelText: 'Password', border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0) ) ), onSaved: (input) => _password = input,
                          obscureText: true,
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(0.0, 10.0, 0, 20.0),
                        child: RaisedButton(
                          
                          padding: EdgeInsets.fromLTRB(100.0, 20.0, 100.0, 20.0),
                          color: Colors.blue,
                          splashColor: Colors.red,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5.0)),
                          onPressed: signin,
                          child: Text('Signin',
                               style: TextStyle(
                                 fontSize: 20.0, color: Colors.white)),
                          
                        ),
                      ),
                    
                      GestureDetector(
                        onTap: (){
                          navigateToSignupScreen();
                        },
                        
                        child: Text("New to Dizitaltrends? Sign up now",
                        style: TextStyle(fontSize: 18.0, color: Colors.green),
                        textAlign: TextAlign.center),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
      
    );
  }
}

SignupPage.dart

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class SignupPage extends StatefulWidget {
  @override
  _SignupPageState createState() => _SignupPageState();
}

class _SignupPageState extends State {

  //Firebase Auth and .instance is use to directly contact to firebase
 // using for grab the form key for our form data
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GlobalKey _formKey = GlobalKey();
//there are three input for signup name, email and password
  String _name, _email, _password;
//check for the current status.
    checkAuthentication() async {
      _auth.onAuthStateChanged.listen((user){
        if (user != null) {
          Navigator.pushReplacementNamed(context, "/");
        }
      });
    }
//if already registered then move to signin
    navigateToSigninScreen(){
      Navigator.pushReplacementNamed(context, "/SigninPage");
    }
  // check the status when application open
  @override
  void initState() {
   
    super.initState();
    this.checkAuthentication();
  }
// signup for formdata to firebase
  signup() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save(); 

      try {
        FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
          email: _email, password: _password)) as FirebaseUser;
          if (user != null) {
            UserUpdateInfo updateuser = UserUpdateInfo();
            updateuser.displayName = _name;
            user.updateProfile(updateuser);
          }
      } catch (e) {
        showError(e.message);
      }

    } 
  }

  showError(String errorMessage){
    showDialog(
      context: context,
      builder: (BuildContext context){
        return AlertDialog(
          title: Text('Error'),
          content: Text(errorMessage),
          actions: [
            FlatButton(
              child: Text("ok"),
              onPressed: (){
                Navigator.of(context).pop();
              },
            )
          ],
        );
      }
    );
  }

  @override
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Signup Page'),
      ),
      body: Container(
        child: Center(
          child: ListView(
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(10.0, 50.0, 10.0, 50.0),
                child: Image(
                  image: AssetImage("assets/logo.png"),
                  width: 100,
                  height: 100,
                ),
              ), 
              Container(
                padding: EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    children: [
                      //email
                      Container(
                        padding: EdgeInsets.all(10.0),
                        child: TextFormField(
                          validator: (input){
                            if (input.isEmpty) {
                              return 'Enter your Name';
                            }
                          },
                          decoration: InputDecoration(
                            labelText: 'Name',
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0)
                            )
                          ),
                          onSaved: (input) => _name = input,
                        ),
                      ),
                      //Name
                      Container(
                        padding: EdgeInsets.all(10.0),
                        child: TextFormField(
                          validator: (input){
                            if (input.length<6) { return 'Email id is must.'; } }, decoration: InputDecoration( labelText: 'Email', border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0) ) ), onSaved: (input) => _email = input,
                        
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.all(10.0),
                        child: TextFormField(
                          validator: (input){
                            if (input.length<6) { return 'Password should be atleast 6 char.'; } }, decoration: InputDecoration( labelText: 'Password', border: OutlineInputBorder( borderRadius: BorderRadius.circular(5.0) ) ), onSaved: (input) => _password = input,
                          obscureText: true,
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 10.0, 0, 20.0),
                        child: RaisedButton(
                          
                          padding: EdgeInsets.fromLTRB(100.0, 20.0, 100.0, 20.0),
                          color: Colors.blue,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5.0)),
                          onPressed: signup,
                          child: Text('Signup',
                               style: TextStyle(
                                 fontSize: 20.0, color: Colors.white)),
                          
                        ),
                      ),
                    
                      GestureDetector(
                        onTap: (){
                          navigateToSigninScreen();
                        },
                        
                        child: Text("Already have account",
                        style: TextStyle(fontSize: 18.0, color: Colors.green),
                        textAlign: TextAlign.center),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
      
    );
  }
}
Content Protection by DMCA.com

Leave a Reply