Thursday, June 13, 2024
Google search engine
HomeDevelopersTwitter Authentication In Flutter

Twitter Authentication In Flutter

Demo module :

Introduction

In this blog, we shall discuss user authentication using firebase in flutter. We will learn authentication using twitter, email, and password, anonymous methods.


Table of content

: Connecting app to firebase

: Installing required package

: Anonymous auth

: Authentication using Email and Password

: Authentication using Twitter


Connecting app to firebase

  1. Open firebase, click on get started which will take you to the Add Project screen.
  2. Enter the project name and complete the other essential steps. It will take you to your project screen, click on the android icon.
  3. Now the steps which are coming are very important so please do them very carefully. You have to enter the package name which is generally your application Id in your app-level build.gradle file. Add the other two optional fields if you wish to add them as well.
  4. Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory. (NOTE: Please check the file that you have downloaded has a google-services.json name or not because if you download it more then one time the name of the file changes to google-services(2).json(for example), so please remove (2) from the file name or rename it to google-services.json)
  5. You will see the following screen.

Here the first block contains the classpath that you have to add into your project level build.gradle file under the dependencies section. The second section contains a plugin and dependencies that you have to add it into your project app-level build.gradle file. Please add these lines properly and carefully if you are adding them for the first time.

Left: project/build.gradle ….Right :project/app/build.gradle

6. Now you should restart your application (NOTE: Please refer full restart not hot reload). Wait for few seconds and your application will be successfully added with firebase. If you see the bellow screen on your firebase then you have successfully added firebase to your app…

Congratulation…

Installing the required package

Update your pubspec.yaml with the following dependency.

flutter_twitter_login | Flutter Package
A Flutter plugin for using the native TwitterKit SDKs on Android and iOS. This plugin uses the new Gradle 4.1 and…pub.dev

firebase_auth | Flutter Package
A Flutter plugin to use the Firebase Authentication API. For Flutter plugins for other Firebase products, see…pub.dev

dependencies:
flutter:
sdk: flutter
firebase_auth: ^latets version
flutter_twitter_login:

Anonymous auth

: Go to the authentication tab in the Firebase console then enable anonymous authentication from the Sign-In Option.

: Sign In Function

Future<void> _signInAnonymously() async {
try {
await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
print(e);
}
}

Try: contains code that may throw an exception.

Catch: used to handle an exception.

This method calls the FirebaseAuth.instance.signInAnonymously() ,return a user.

: Sign Out Function

Future<void> _signOut() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e);
}
}

This method triggers the signOut method to signOut the user.


Authentication using Email and Password

: Setting up the variables

final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;

NOTE: FirebaseAuth is the entry point of the FirebaseAuthenticationSDK.

: Sign In Function

void _signInWithEmailAndPassword() async {
await _auth.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
}

signInWithEmailAndPassword() method sign in a user with the given email address and password.

If sign In successful, it also signs the user in into the app and updates
the
onAuthStateChanged stream.

If sign In is unsuccessful, it shows three types of error:-

  1. ERROR_WEAK_PASSWORD: If the password is not strong enough.
  2. ERROR_INVALID_EMAIL: If the email address is malformed.
  3. ERROR_EMAIL_ALREADY_IN_USE: If the email is already in use by a different account.

: Sign Up Function

_signUpWithEmailAndPassword() async {
await _auth.createUserWithEmailAndPassword(
email: _emailController.text, password: _passwordController.text);
}

createUserWithEmailAndPassword() create a new user account with the given email address and password.

If successful, it also signs the user into the app and updates the onAuthStateChanged stream.

You must enable Email & Password accounts in the Auth section of the Firebase console before being able to use them.

If sign In is unsuccessful, it show error:-

  1. ERROR_INVALID_EMAIL — If the [email] address is malformed.
  2. ERROR_WRONG_PASSWORD — If the [password] is wrong.
  3. ERROR_USER_NOT_FOUND — If there is no user corresponding to the given [email] address, or if the user has been deleted.
  4. ERROR_USER_DISABLED — If the user has been disabled (for example, in the Firebase console)
  5. ERROR_TOO_MANY_REQUESTS — If there were too many attempts to sign in as this user.
  6. ERROR_OPERATION_NOT_ALLOWED — Indicates that Email & Password accounts are not enabled.

: Sign Out Function

_logOut() async {
try {
await _auth.signOut();
Navigator.of(context).pop();
} catch (error) {
print(error);
}
}

signOut() method Signs out the current user and clears it from the disk cache.

If successful, it signs the user out of the app and updates the onAuthStateChanged stream.

: Reset Password Function

_resetPassword() async {
try {
_auth.sendPasswordResetEmail(email: email);
} catch (error) {
print(error);
}
}

sendPasswordResetEmail() method triggers the Firebase Authentication backend to send a password reset email to the given email address, which must correspond to an existing user of your app.

If it is unsuccessful then it gives error:

  1. ERROR_INVALID_EMAIL — If the email address is malformed.
  2. ERROR_USER_NOT_FOUND — If there is no user corresponding to the given email address.

Authentication using Twitter

Setting up the Project

  1. Plugin Used

flutter_twitter | Flutter Package
A Flutter plugin for using the native TwitterKit SDKs on Android and iOS. This plugin uses the new Gradle 4.1 and…pub.dev

2. Go to https://apps.twitter.com/ and make a developer account.

NOTE: Do not forget to add the callback URLs. You need to add three callback URL

  • for android:twittersdk: //,
  • for ios: twitterkit-CONSUMERKEY: //
  • add the URL that you get while enabling the twitter authentication from firebase.

You can add URL only for ios or for android.

3. Enable twitter sign-in option in the firebase console. (Paste the consumerKey, consumerSecret in the API key and API secret section respectively)

3. Click enable

We are now ready to go

: FirebaseAuth instance

Let’s create a firebase auth instance.

FirebaseAuth _auth = FirebaseAuth.instance;

: TwitterLogin

flutter_twitter_login provides us TwitterLogin class that takes consumerKey and consumerSecret that we got during creating the twitter developer account.

final TwitterLogin twitterLogin = new TwitterLogin(
consumerKey: 'YOUR CONSUMERKEY',
consumerSecret: 'YOUR SECRETKEY',
);

: Sign In Function

void _signInWithTwitter(String token, String secret) async {
final AuthCredential credential = TwitterAuthProvider.getCredential(
authToken: token, authTokenSecret: secret);
await _auth.signInWithCredential(credential);
}

: Logging in User

void _login() async {
final TwitterLoginResult result = await twitterLogin.authorize();
String newMessage;
if (result.status == TwitterLoginStatus.loggedIn) {
_signInWithTwitter(result.session.token, result.session.secret);
} else if (result.status == TwitterLoginStatus.cancelledByUser) {
newMessage = 'Login cancelled by user.';
} else {
newMessage = result.errorMessage;
}

setState(() {
message = newMessage;
});
}

: LogOut

void _logout() async {
await twitterLogin.logOut();
await _auth.signOut();
}

: Full code

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (ctx, userSnapshot) {
if (userSnapshot.hasData) {
return LogOut();
} else if (userSnapshot.hasError) {
return CircularProgressIndicator();
}
return SignInScreen();
},
),
);
}
}

class SignInScreen extends StatefulWidget {
@override
_SignInScreenState createState() => _SignInScreenState();
}

class _SignInScreenState extends State<SignInScreen> {
String message;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.network(
"https://www.3nions.com/wp-content/uploads/2020/01/comp_1.gif",
height: 200,
),
InkWell(
onTap: () {
_login();
},
borderRadius: BorderRadius.circular(30),
splashColor: Colors.blue,
child: Container(
height: 50,
width: 300,
child: Center(
child: Text(
"Sign In using twitter",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.blue,
width: 3,
)),
),
),
SizedBox(
height: 20,
),
Text(
message == null ? "" : message,
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
),
),
InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) {
return EmailPasswordScreen();
},
));
},
borderRadius: BorderRadius.circular(30),
splashColor: Colors.blue,
child: Container(
height: 50,
width: 300,
child: Center(
child: Text(
"Sign In using email and password",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.blue,
width: 3,
)),
),
),
SizedBox(
height: 40,
),
InkWell(
onTap: () {
_signInAnonymously();
},
borderRadius: BorderRadius.circular(30),
splashColor: Colors.blue,
child: Container(
height: 50,
width: 300,
child: Center(
child: Text(
"Sign In as anonymous user",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.blue,
width: 3,
)),
),
),
],
),
),
);
}

void _login() async {
final TwitterLoginResult result = await twitterLogin.authorize();
String newMessage;
if (result.status == TwitterLoginStatus.loggedIn) {
_signInWithTwitter(result.session.token, result.session.secret);
} else if (result.status == TwitterLoginStatus.cancelledByUser) {
newMessage = 'Login cancelled by user.';
} else {
newMessage = result.errorMessage;
}

setState(() {
message = newMessage;
});
}
}

final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
FirebaseAuth _auth = FirebaseAuth.instance;

final TwitterLogin twitterLogin = new TwitterLogin(
consumerKey: '',
consumerSecret: '',
);

void _signInWithTwitter(String token, String secret) async {
final AuthCredential credential = TwitterAuthProvider.getCredential(
authToken: token, authTokenSecret: secret);
await _auth.signInWithCredential(credential);
}

void _signInWithEmailAndPassword() async {
await _auth.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
}

_signUpWithEmailAndPassword() async {
await _auth.createUserWithEmailAndPassword(
email: _emailController.text, password: _passwordController.text);
}

Future<void> _signInAnonymously() async {
try {
await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
print(e);
}
}

_logout() async {
await twitterLogin.logOut();
await _auth.signOut();
}




class LogOut extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Auth Demo"),
),
body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, snapshot) {
FirebaseUser firebaseUser = snapshot.data;
return snapshot.hasData
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"SignIn Success 😊",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
SizedBox(
height: 20,
),
Text("UserId: ${firebaseUser.uid}"),
SizedBox(
height: 20,
),
firebaseUser.photoUrl == null
? SizedBox(
height: 0,
)
: Image.network(
firebaseUser.photoUrl,
height: 100,
),
Text("Your name: ${firebaseUser.displayName}"),
Text("Your email: ${firebaseUser.email}"),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () {
_logout();
},
child: Text(
"LogOut",
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
)
],
),
)
: CircularProgressIndicator();
},
),
);
}
}

class EmailPasswordScreen extends StatefulWidget {
@override
_EmailPasswordScreenState createState() => _EmailPasswordScreenState();
}

class _EmailPasswordScreenState extends State<EmailPasswordScreen> {
bool isSingIn = true;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Enter your email password",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 25),
),
Card(
elevation: 5,
child: TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: "Email", prefixIcon: Icon(Icons.email)),
),
),
Card(
elevation: 5,
child: TextField(
controller: _passwordController,
decoration: InputDecoration(
hintText: "Password", prefixIcon: Icon(Icons.lock_outline)),
),
),
RaisedButton(
color: Colors.blue,
onPressed: () {
isSingIn
? _signInWithEmailAndPassword()
: _signUpWithEmailAndPassword();
Navigator.of(context).pop();
},
child: Text(
isSingIn ? "Sign In" : "Sign Up",
style: TextStyle(color: Colors.white),
),
),
FlatButton(
onPressed: () {
setState(() {
isSingIn = !isSingIn;
});
},
child: Text(
isSingIn ? "Create an account" : "Already have an account"))
],
),
),
);
}
}

: GitHub Link

flutter-devs/twitter_auth_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

: If you want to perform local authentication using fingerprint, you can read the my blog post on Local Authentication in Futter .

Local Authentication in Flutter
Local Authentication in Fluttermedium.com

Google Sign In With Flutter
Google sign-in with Flutter using Firebase authenticationmedium.com

Phone Authentication in Flutter
Building a phone number authentication flutter appmedium.com


Thanks for Reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

If we got something wrong? Let me know in the comments. we would love to improve.


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments