Open In App

Flutter – Implementing Signing Out the User

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we can learn how to Signout the user from a flutter application. This article is a continuation of the article that explains making google signIn UI and its authentication. It is recommended to check the same before moving ahead.

Now we will implement the Sign out feature for the flutter application.

Implementation:

Follow the below steps to implement logout feature in Flutter:

Step 1: Just open your homePage.dart file.

Step 2:  In Scaffold, call the floatingActionButton widget, further onpressed property called the signOut function.

Step 3: In child property, we have to give the Icon of logout, a background color is Green.

We are good to go. Now let’s define the signOut function that we need.

Step 4: Now first of all make the firebaseAuth instance ‘auth‘.

Step 5: Above the @override ,  just define the function. This function will be async . Now by using auth call the signOut( ) inbuilt method.

Step 6: After that, we simply call the navigator to push the sign-up screen.

Now our updated homepage.dart file : 

Dart




import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:googlesign/signup.dart';
 
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  final FirebaseAuth auth = FirebaseAuth.instance;
  //signout function
  signOut() async {
    await auth.signOut();
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => SignInScreen()));
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.green,
        title: Text("GEEKS FOR GEEKS"),
      ),
       
      //  floating Action Button using for signout ,
 
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          signOut();
        },
        child: Icon(Icons.logout_rounded),
        backgroundColor: Colors.green,
      ),
 
      body: Center(
        child: Text("Home page"),
      ),
    );
  }
}


If we pressed the button, we log out of the application and move to the sign-in screen. But there  is a problem if we again open the application without signout, we don’t directly navigate to the Homepage, we have to again signIn the Application. This is the big problem. 

Now let’s solve this, if we create a bool variable “islogin” and make it true when we actually signed in, and make it false when we signOut the Application. Now we can check islogin value during the initializing of the application, If islogin is true we go to the home screen else to signIn screen. We can store the value in sharedPreferences.

Let’s just do it now:

add  shared_preferences: ^2.0.6  in pubspec yaml file.

Step 7: Create a new file shared.dart, and import the package library.

Step 8:  Make a class “Share” and make two functions for saving data and reading data respectively.

Dart




import 'package:shared_preferences/shared_preferences.dart';
 
class Shared {
  static String loginSharedPreference = "LOGGEDINKEY";
 
  // save data
 
  static Future<bool> saveLoginSharedPreference(islogin) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setBool(loginSharedPreference, islogin);
  }
 
  //fetch data
 
  static Future getUserSharedPreferences() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.getBool(loginSharedPreference);
  }
}


Now open your main.dart file, and make the following changes.

Dart




import 'package:flutter/material.dart';
import 'package:googlesign/homepage.dart';
import 'package:googlesign/share.dart';
import 'package:googlesign/signup.dart';
import 'package:firebase_core/firebase_core.dart';
 
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(); // initializing the firebase app
  runApp(GoogleSignIn()); // calling runApp
}
 
// google signin stateful widget
class GoogleSignIn extends StatefulWidget {
  GoogleSignIn({Key? key}) : super(key: key);
  @override
  _GoogleSignInState createState() => _GoogleSignInState();
}
 
class _GoogleSignInState extends State<GoogleSignIn> {
  var islogin;
 
  checkUserLoginState() async {
    await Shared.getUserSharedPreferences().then((value) {
      setState(() {
        islogin = value;
      });
    });
  }
 
  @override
  void initState() {
    checkUserLoginState();
    super.initState();
  }
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GEEKS FOR GEEKS',
      debugShowCheckedModeBanner:
          false, // debug banner false that is show on corner
      theme: ThemeData(
        primarySwatch: Colors.cyan, // color to our app
      ),
      home: islogin != null
          ? islogin
              ? HomePage()
              : SignInScreen()
          : SignInScreen(),
    );
  }
}


Output :  



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads