deploying-a-flutter-app-with-firebase-authentication-and-firestore.html

Deploying a Flutter App with Firebase Authentication and Firestore

Flutter has revolutionized mobile app development with its cross-platform capabilities and rich UI components. To enhance your app's functionality, integrating Firebase services like Authentication and Firestore can take your app to the next level. In this article, we’ll walk you through deploying a Flutter app that utilizes Firebase Authentication for user management and Firestore for data storage.

What is Firebase?

Firebase is a platform developed by Google that provides various tools to help developers build high-quality apps, improve app quality, and grow their user base. Key features include:

  • Firebase Authentication: Simplifies user registration and sign-in processes.
  • Cloud Firestore: A flexible, scalable database for storing and syncing data.

Use Cases for Firebase in Flutter Apps

Before we dive into the code, let's discuss some common use cases for integrating Firebase Authentication and Firestore:

  • User Authentication: Allow users to sign up and log in using email, Google, or other providers.
  • Real-Time Data Sync: Store and retrieve user data in real-time, enabling seamless updates across devices.
  • User Profiles: Store user-specific data, such as preferences and settings.

Setting Up Your Flutter App

Step 1: Create a New Flutter Project

First, ensure you have Flutter installed on your system. Open your terminal and create a new Flutter project by running:

flutter create flutter_firebase_app
cd flutter_firebase_app

Step 2: Add Firebase to Your Project

  1. Create a Firebase Project: Go to the Firebase Console, click on "Add project," and follow the prompts.

  2. Add an Android App:

  3. Register your app with the package name (e.g., com.example.flutterfirebaseapp).
  4. Download the google-services.json file and place it in the android/app directory.

  5. Add an iOS App (if applicable):

  6. Register your iOS app with the bundle ID.
  7. Download the GoogleService-Info.plist file and place it in the ios/Runner directory.

Step 3: Configure Dependencies

Update your pubspec.yaml file to include the necessary Firebase packages:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: latest_version
  firebase_auth: latest_version
  cloud_firestore: latest_version

Run flutter pub get to install the packages.

Step 4: Initialize Firebase

In your main.dart file, initialize Firebase as follows:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase App',
      home: HomeScreen(),
    );
  }
}

Implementing Firebase Authentication

Step 5: Create Authentication Logic

Create a new file named auth_service.dart:

import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Sign up with email and password
  Future<User?> signUp(String email, String password) async {
    UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
    return result.user;
  }

  // Sign in with email and password
  Future<User?> signIn(String email, String password) async {
    UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
    return result.user;
  }

  // Sign out
  Future<void> signOut() async {
    await _auth.signOut();
  }
}

Step 6: Create the Authentication UI

In your home_screen.dart, create a basic UI for user authentication:

import 'package:flutter/material.dart';
import 'auth_service.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final AuthService _authService = AuthService();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  void _signIn() async {
    final user = await _authService.signIn(_emailController.text, _passwordController.text);
    if (user != null) {
      // Navigate to the main app screen
      print("User signed in: ${user.email}");
    }
  }

  void _signUp() async {
    final user = await _authService.signUp(_emailController.text, _passwordController.text);
    if (user != null) {
      // Navigate to the main app screen
      print("User signed up: ${user.email}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Flutter Firebase Authentication')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(controller: _emailController, decoration: InputDecoration(labelText: 'Email')),
            TextField(controller: _passwordController, decoration: InputDecoration(labelText: 'Password'), obscureText: true),
            ElevatedButton(onPressed: _signIn, child: Text('Sign In')),
            ElevatedButton(onPressed: _signUp, child: Text('Sign Up')),
          ],
        ),
      ),
    );
  }
}

Using Firestore for Data Storage

Step 7: Set Up Firestore

To use Firestore, update your pubspec.yaml to ensure you have the cloud_firestore package added, as shown earlier.

Step 8: Create Firestore Service

Create a file named firestore_service.dart to handle Firestore operations:

import 'package:cloud_firestore/cloud_firestore.dart';

class FirestoreService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  // Add user data to Firestore
  Future<void> addUserData(String uid, String email) async {
    await _db.collection('users').doc(uid).set({'email': email});
  }

  // Retrieve user data
  Future<Map<String, dynamic>?> getUserData(String uid) async {
    DocumentSnapshot snapshot = await _db.collection('users').doc(uid).get();
    return snapshot.data();
  }
}

Step 9: Integrate Firestore in Your App

In your HomeScreen, after signing up or signing in a user, you can add their data to Firestore:

import 'firestore_service.dart';

final FirestoreService _firestoreService = FirestoreService();

void _signUp() async {
  final user = await _authService.signUp(_emailController.text, _passwordController.text);
  if (user != null) {
    await _firestoreService.addUserData(user.uid, user.email!);
    print("User signed up and data added: ${user.email}");
  }
}

Troubleshooting Common Issues

  • Firebase Initialization Errors: Ensure that you’ve added the google-services.json and GoogleService-Info.plist files correctly.
  • Dependency Conflicts: Run flutter pub get regularly to keep your packages updated.
  • Firestore Permissions: Check your Firestore rules in the Firebase console to ensure your app has permission to read and write data.

Conclusion

Deploying a Flutter app with Firebase authentication and Firestore can significantly enhance your app's functionality and user experience. By following this guide, you now have a robust framework for user management and data storage. Whether you’re building a simple app or a complex project, Firebase provides the tools necessary to create a seamless user experience. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.