Flutter firebase authentication tutorial

 

Flutter Firebase Authentication :

Flutter firebase authentication is used to implement login mechanism in the flutter app. This is a easiest way to provide user login based on third party providers (E-Mail accounts).

Also you can create your own credentials which can be stored in firebase and is used to validate user which we have seen in this part of the tutorial.

In this part of the tutorial we have explained implementation details for both android and iOS devices right from the basic configuration to the sign up process.

In coming tutorials we will see login using different providers like Google, facebook, twitter and so on.

We have also covered firebase console level configurations in the video tutorial.

 

pubspec.yaml :

We have specified the firebase authentication and firebase core libraries.Specify the version latest available to avoid any code level conflicts.

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^3.1.3
  firebase_core: ^1.7.0

 

 

Flutter Firebase Authentication Video Tutorial :

Go through the below tutorial for more detailed updates.

 

main.dart :

Initialize the Flutter firebase authentication

WidgetsFlutterBinding.ensureInitialized(); 
await Firebase.initializeApp();

 

 

Add boolean variables to know the initialize status and also error status.

bool _initialized = false; 
bool _error = false;

 

 

Specify the method flutterfirebasefire which is async method.And set the boolean variables to true based on the initialization status.

void flutterFirebaseInit() async {
  try {
    await Firebase.initializeApp();
    setState(() {
      _initialized = true;
    });
  } catch (e) {
    setState(() {
      _error = true;
    });
  }
}

 

 

Provide init() state and specify the method.

@override
void initState() {
  super.initState();
  flutterFirebaseInit();
}

 

 


Now with the help of boolean variable handle progress.

if (_error) {
  return errorHandle();
}
if (!_initialized) {
  return progressHandle();
}

 


For handling error status we have returned a text widget

Widget errorHandle() {
  return Center(
    child: Text("There is an error"),
  );
}

 

 

For handling progress status we returned

Widget progressHandle() {
  return Center(
    child: CircularProgressIndicator(),
  );
}

 

For handling initialized state for flutter firebase authentication

Widget initialized() {
  var usernameController = TextEditingController();
  var passwordController = TextEditingController();
  return Center(
    child: Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        children: [
          TextField(
            controller: usernameController,
          ),
          TextField(
            controller: passwordController,
          ),
          TextButton(
            onPressed: () async {
              try {
                UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
                  email: usernameController.text.toString(),
                  password: passwordController.text.toString(),
                );
              } 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);
              }
            },
            child: Text("Sign-Up"),
          ),
        ],
      ),
    ),
  );
}

 

 

 

Full Code:

Provide the full code for flutter firebase authentication.We have considered a basic view with the help of which we accept user input.

Email and password is accepted and is validate by sending to the firebase and as status is received it will be validated or signed-up based on the process.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Firebase Authentication"),
        ),
        body: App(),
      ),
    );
  }
}

class App extends StatefulWidget {
  const App({Key? key}) : super(key: key);

  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  bool _initialized = false;
  bool _error = false;

  void flutterFirebaseInit() async {
    try {
      await Firebase.initializeApp();
      setState(() {
        _initialized = true;
      });
    } catch (e) {
      setState(() {
        _error = true;
      });
    }
  }

  @override
  void initState() {
    flutterFirebaseInit();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (_error) {
      return errorHandle();
    }
    if (!_initialized) {
      return progressHandle();
    }
    return initialized();
  }
}

Widget errorHandle() {
  return Center(
    child: Text("There is an error"),
  );
}

Widget progressHandle() {
  return Center(
    child: Text("This is a progress bar section"),
  );
}

Widget initialized() {
  var usernameController = TextEditingController();
  var passwordController = TextEditingController();
  return Center(
    child: Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        children: [
          TextField(
            controller: usernameController,
          ),
          TextField(
            controller: passwordController,
          ),
          TextButton(
            onPressed: () async {
              try {
                UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
                  email: usernameController.text.toString(),
                  password: passwordController.text.toString(),
                );
              } 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);
              }
            },
            child: Text("Sign-Up"),
          ),
        ],
      ),
    ),
  );
}

 


Output :

This screen illustrates the utilization of Firebase Authentication.

Flutter firebase authentication

 

If you have any questions or queries regarding this Firebase Authentication tutorial, feel free to leave them in the comments section below.

If you found this tutorial helpful, don’t hesitate to like and share for more insightful updates

 

Show Buttons
Hide Buttons
Read previous post:
Deep linking in flutter | dynamic link

  Deep linkingĀ  : Deep linking concept in flutter app is explained in this part of the tutorial. When you...

Close