Flutter Firebase Anonymous Authentication Tutorial

Flutter Firebase Anonymous Authentication Tutorial

In this tutorial, We will be building an app to demonstrate flutter firebase anonymous authentication. Flutter Firebase is the most popular cloud platform. Firebase Anonymous Authentication comes in handy and a security layer to call firebase cloud. Instead of having security rules be open to all, make it to only authenticated users only.

We will build a splash screen to login as anonymous and land users on home screen.

Step 1:

Go to to firebase website create a project.Creating a project is straight forward and register your app by providing package name and debug SHA -1 key.Download the googleservices.json file and add it to android/app directory.

Step 2:

Go to android/build.gradle file (Project level gradle) and add below classpath.

Add google maven to repository to download gradle plugin.

buildscript {

  repositories {
    google() 
  }

  dependencies {

    classpath 'com.google.gms:google-services:4.3.8'  
  }
}

allprojects {

  repositories {
    google()  
  }
}

Step 3:

Go to android/app/build.gradle (App level gradle) and add below line at top of file

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'  

android {
}

Step 4:

Add the following dependency.

dependencies {
  implementation platform('com.google.firebase:firebase-bom:28.0.1')

  implementation 'com.google.firebase:firebase-auth'
}

Step 5:

Now create a splash_view.dart file and type in stfull autocomplete phrase to create a stateful widget and name it SplashView and now override initstate method and run a future to run it for 2 sec as splash time.SplashView requires a AuthService class injected at constructor.

AuthService is service class to write all code related to only authentication and call methods on view classes.

On initstate after 2 seconds future is complete we will check whelther user has any previous login session or not and if there is not previous login we will login through firebase anonymous login.If user is having previous firebase user credentials we will navigate user to HomeView.

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

void _runTimer() async{
  Future.delayed(Duration(seconds: 2), () {
    _checkLogin();
  });
}

void _checkLogin() async{
  var user = await widget._authService.getFirebaseCurrentUser();
  if(user == null){
    var userCred = await widget._authService.signInAnonymously();
    checkUserCreds(userCred);
  }else{
    Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomeView()));

  }

}

void checkUserCreds(UserCredential userCredential){
  if(userCredential == null){
    Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomeView()));
  }
}

Here is full code below.

import 'package:flutter/material.dart';
import 'package:flutter_anonymous_app/auth_service.dart';
import 'package:flutter_anonymous_app/splash_view.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Anonymous Login',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SplashView(authService: AuthService(),),
    );
  }
}
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import 'auth_service.dart';
import 'home_view.dart';

class SplashView extends StatefulWidget {
  AuthService _authService;

  SplashView({@required AuthService authService}):_authService = authService;

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

class _SplashViewState extends State<SplashView> {

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

  void _runTimer() async{
    Future.delayed(Duration(seconds: 2), () {
      _checkLogin();
    });
  }

  void _checkLogin() async{
    var user = await widget._authService.getFirebaseCurrentUser();
    if(user == null){
      var userCred = await widget._authService.signInAnonymously();
      checkUserCreds(userCred);
    }else{
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomeView()));

    }

  }

  void checkUserCreds(UserCredential userCredential){
    if(userCredential == null){
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomeView()));
    }
  }

  @override
  Widget build(BuildContext context) {
    return _buildSplash();
  }
}


Widget _buildSplash(){
  return Container(
    color: Colors.grey[50],
    child: _buildCenter(),

  );
}


Widget _buildCenter(){
  return  Center(
    child: Column(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
            margin: EdgeInsets.all(16.0),
            child: Icon(Icons.account_box)),
        Container(
            margin: EdgeInsets.all(16.0),
            child: CircularProgressIndicator())
      ],
    ),
  );

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

class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home'),),
      body: Center(
        child: Text("Home View",style: TextStyle(fontSize: 22),),
      ),
    );
  }
}


import 'package:firebase_auth/firebase_auth.dart';

class AuthService{
  final  _firebaseAuth = FirebaseAuth.instance;

  Future<User> getFirebaseCurrentUser() async{
   return  _firebaseAuth.currentUser;
  }

  Future<UserCredential> signInAnonymously() async {
    return _firebaseAuth.signInAnonymously();
  }

  Future<bool> signOut() async{
    await _firebaseAuth.signOut();
    var user = await getFirebaseCurrentUser();
    if(user != null){
      return false;
    }else{
      return true;
    }
  }



}