Open In App

Flutter – Firebase GitHub Authentication

Last Updated : 26 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

GitHub is like a digital hub for code. Imagine it as a virtual space where developers team up to build amazing things. It stores and tracks changes to code, making it easy for everyone to collaborate, contribute, and create software together. It’s the cool place where coding magic happens. Since GitHub is a version control system that every developer should be familiar with, we might wish to create apps on top of it. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

StStep 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Add SignUp with GitHub button and text for getting whether the user has signup/login or not on the screen

We have added 1 bool variable

Dart




bool isSignSuccess = false;


Then we added 2 text and 1 Floating Action Button.

Dart




Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("SignIn with Github Template"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have signed in or not',
            ),
            // Here we have shown tthe bool variable
            Text(
              '$isSignSuccess',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      // This button is for signing up with github account
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
            
        },
        tooltip: 'Sign with Github',
        label: const Text("Sign with Github"),
      ),
    )


Step 3: Add the package github_sign_in_plus in project

Dart




github_sign_in_plus: ^0.0.1


You can refer this for getting latest version: github_sign_in_plus

Step 4: Create a firebase project

  • Create a firebase project on this: Click here
  • Add Authenication and SignIn method as github

Here you will require client id and client secret which we will get in next step

Step 5: Create a github developer account for getting API keys

To add the functionality for github signing we will require 3 things clientId, clientSecret, redirectUrl. Let’s learn how we can do that

Step 5.1: Create OAuth Application from here

Add the following and submit the form

  • Application name: Application name that you want to show to customer
  • Homepage URL: URL to our application homepage
  • Authorization callback URL: You can get this from firebase

In step 4 you must have recieve this type of screen

WhatsApp-Image-2023-11-25-at-83624-PM-(1)

Copy the url and add that in Authorization callback URL and env file of your app

Step 5.2: Generate Client secret from page opens when you complete first step

Store the client ID and client secret and add it in .env file as well in firebase app created in previous app.

WhatsApp-Image-2023-11-25-at-83624-PM

Step 6: Add the client id and client secret in Flutter

Now add the client id and client secret that you get in previous steps in env file and store that in variables. To know about how to use env file in flutter check out this article How to Add .env File in Flutter.

Sample .env file

CLIENT_ID=””;

CLIENT_SECRET=””;

REDIRECT_URL=””;

Step 7: Add the following code on onPressed of button

This code will open the github page so that user can enter credential

Dart




final GitHubSignIn gitHubSignIn = GitHubSignIn(
          clientId: dotenv.env["CLIENT_ID"] ?? "",
          clientSecret: dotenv.env["CLIENT_SECRET"] ?? "",
          redirectUrl: dotenv.env["REDIRECT_URL"] ?? "");
          // From this we will be redirect to login page
          // of github to get the token
          var result = await gitHubSignIn.signIn(context);
          // To get status whether user is logged in or not
          switch (result.status) {
            // If it is success it will come here
            case GitHubSignInResultStatus.ok:
              print(result.token);
               isSignSuccess = true;
              setState(() {});
              break;
  
            case GitHubSignInResultStatus.cancelled:
            // If it is cancelled by user 
            // it will come here
            case GitHubSignInResultStatus.failed:
              // If it is failed due to any reason
              // it will come here
              print(result.errorMessage);
              break;
          }


Here you have successfully implement login with github!!

Complete Code

Dart




import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:github_sign_in_plus/github_sign_in_plus.dart';
  
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  dotenv.load(fileName: "lib/.env");
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  // This widget is the root of your application
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  // To check user is signed up or not
  bool isSignSuccess = false
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("SignIn with Github Template"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have signed in or not',
            ),
            // Here we have shown tthe bool variable
            Text(
              '$isSignSuccess',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      // This button is for signing up with github account
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          final GitHubSignIn gitHubSignIn = GitHubSignIn(
              clientId: dotenv.env["CLIENT_ID"] ?? "",
              clientSecret: dotenv.env["CLIENT_SECRET"] ?? "",
              redirectUrl: dotenv.env["REDIRECT_URL"] ?? "");
          // From this we will be redirect to login page
          // of github to get the token
          var result = await gitHubSignIn.signIn(context);
          // To get status whether user is logged in or not
          switch (result.status) {
            // If it is success it will come here
            case GitHubSignInResultStatus.ok:
              print(result.token);
               isSignSuccess = true;
              setState(() {});
              break;
  
            case GitHubSignInResultStatus.cancelled:
            // If it is cancelled by user it will come here
            case GitHubSignInResultStatus.failed:
              // If it is failed due to any
              // reason it will come here
              print(result.errorMessage);
              break;
          }
        },
        tooltip: 'Sign with Github',
        label: const Text("Sign with Github"),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads