Sign In with GitHub in Flutter
Tags: github, flutter, firebase, dart
Published: 2024-02-22 22:18:05

I wanted to implement GitHub authentication in a flutter mobile application.
I discovered this tutorial on medium :

[medium.com/@dotronglong/sign-in-with-github-in-flutter](https://medium.com/@dotronglong/sign-in-with-github-in-flutter-8649ab78f5d6?source=post_page-----3a9731177986--------------------------------)

But the flutter package isn’t updated, so I’d like to talk about another flutter package to help you implement github authentication.

> Summary : [

GitHub App

In order to start, you will need to create a GitHub OAuth application. Please access to [https://github.com/settings/developers](https://github.com/settings/developers) and create an application.

After creating app, you can see Client ID and Client Secret , callback URL would be your firebase project callback URL. It is something similar to [https://yourapp.firebaseapp.com/__/auth/handler](https://yourapp.firebaseapp.com/__/auth/handler)

Enable Firebase GitHub

Next, we need to enable firebase’s github sign in method, and provide client id and client secret to firebase.

]

To insall the package : [github_sign_in_plus](https://pub.dev/packages/github_sign_in_plus)

```dart
flutter pub add github_sign_in_plus
```

Other packages : http and shared_preferences

```dart
flutter pub add http  
flutter pub add shared_preferences
```
In your main page, add the following code and test it…

```dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:github_sign_in_plus/github_sign_in_plus.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GitHubSignIn gitHubSignIn = GitHubSignIn(
    clientId: 'Your clientId',
    clientSecret: 'Your clientSecret',
    redirectUrl: 'Your firebase redirectUrl',
    title: 'GitHub Connection',
    centerTitle: false,
  );

  bool _isConnected = false;
  String _username = '';

  @override
  void initState() {
    super.initState();
    // Check connection status when starting the application
    _checkLoggedIn();
  }

  void _checkLoggedIn() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isConnected = prefs.getBool('isConnected') ?? false;
    String username = prefs.getString('username') ?? '';
    setState(() {
      _isConnected = isConnected;
      _username = username;
    });
  }

  void _gitHubSignIn(BuildContext context) async {
    var result = await gitHubSignIn.signIn(context);
    switch (result.status) {
      case GitHubSignInResultStatus.ok:
        String accessToken = result.token.toString();
        http.Response response = await http.get(
          Uri.parse('https://api.github.com/user'),
          headers: {
            'Authorization': 'token $accessToken',
            'Accept': 'application/json',
          },
        );

        if (response.statusCode == 200) {
          //Analyze the JSON response
          Map<String, dynamic> userData = json.decode(response.body);
          String username = userData['login'];
          setState(() {
            _isConnected = true;
            _username = username;
          });
          // Save connection status
          SharedPreferences prefs = await SharedPreferences.getInstance();
          prefs.setBool('isConnected', true);
          prefs.setString('username', username);
        } else {
          print('Error retrieving user information');
        }
        //print("Sign-in successful")
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Sign-in successful'),
            duration: Duration(seconds: 5),
          ),
        );
        break;

      case GitHubSignInResultStatus.cancelled:
      case GitHubSignInResultStatus.failed:
        setState(() {
          _isConnected = false;
        });
        print(result.errorMessage);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Sign-in failed: ${result.errorMessage}'),
            duration: const Duration(seconds: 5),
          ),
        );
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("0xApp"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (!_isConnected)
              ElevatedButton(
                onPressed: () {
                  _gitHubSignIn(context);
                },
                child: const Text("GitHub Connection"),
              ),
            if (_isConnected)
              Text(
                'Connected as $_username',
                style: const TextStyle(fontSize: 20),
              ),
          ],
        ),
      ),
    );
  }
}

```
Then admire the result …

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ku9v415tcaqgh7dgvryy.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lim30fwjrrfeiqe98oaw.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3iln0gwptj1a0k7zk31e.png)

> Summary

The code above implements a Flutter application that allows users to log in with their GitHub account. It uses the `github_sign_in_plus` package to handle authentication via GitHub. Login information is stored locally using the `shared_preferences` package, and the application displays the logged-in username once authenticated.