Implementing User Authentication in Flutter

 Implementing user authentication in Flutter typically involves using Firebase Authentication or a custom backend. Here's a step-by-step guide for both Firebase Authentication (most common and beginner-friendly) and custom backend authentication.


🔐 Option 1: Firebase Authentication

✅ Setup

  1. Add Firebase to Your Flutter App

    • Go to Firebase Console.

    • Create a new project.

    • Register your app (iOS/Android).

    • Download google-services.json (Android) or GoogleService-Info.plist (iOS) and add it to the app.

  2. Add Firebase dependencies

In pubspec.yaml:

yaml
dependencies: firebase_core: ^2.10.0 firebase_auth: ^4.6.0

Then run:

bash
flutter pub get
  1. Initialize Firebase

In main.dart:

dart
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); }

🔑 Email & Password Authentication

Sign Up

dart
Future<void> signUp(String email, String password) async { try { await FirebaseAuth.instance.createUserWithEmailAndPassword( email: email, password: password, ); } catch (e) { print('Sign up error: $e'); } }

Sign In

dart
Future<void> signIn(String email, String password) async { try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: email, password: password, ); } catch (e) { print('Sign in error: $e'); } }

Sign Out

dart
Future<void> signOut() async { await FirebaseAuth.instance.signOut(); }

Auth State Listener

dart
FirebaseAuth.instance.authStateChanges().listen((User? user) { if (user == null) { print('User is currently signed out!'); } else { print('User is signed in!'); } });

🧰 Option 2: Custom Backend Authentication (JWT-based)

You’ll need:

  • A backend API (Node, Django, Laravel, etc.)

  • HTTP client in Flutter

Add dependencies

yaml
dependencies: http: ^0.13.5 shared_preferences: ^2.2.1

Example login function

dart
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; Future<void> login(String email, String password) async { final url = Uri.parse('https://your-api.com/login'); final response = await http.post( url, body: {'email': email, 'password': password}, ); if (response.statusCode == 200) { final data = jsonDecode(response.body); final token = data['token']; final prefs = await SharedPreferences.getInstance(); await prefs.setString('auth_token', token); } else { print('Login failed: ${response.body}'); } }

🧪 Next Steps

  • Add Google/Facebook Sign-in (via google_sign_in, flutter_facebook_auth)

  • Use Provider or Riverpod to manage auth state

  • Secure tokens with flutter_secure_storage instead of shared_preferences


GET DIRECTIONS

Comments

Popular posts from this blog

Integrating WebSockets with React and Python Backend

Oracle Fusion Cloud vs. On-Premise: Which One is Right for You?

Named Routes vs. Anonymous Routes in Flutter