0Pricing
Flutter Mobile Development · درس

إعداد Firebase والمصادقة

أعدّ Firebase في مشروع Flutter لديك ونفّذ مصادقة المستخدم باستخدام البريد الإلكتروني/كلمة المرور وGoogle Sign-In وموفّرين آخرين

إعداد Firebase والمصادقة درس مجاني في Flutter Mobile Development على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Flutter Mobile Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Flutter Mobile Development 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Firebase for Flutter Apps

Welcome to Firebase integration! Firebase is a powerful platform by Google that offers many backend services for your mobile and web applications.

It acts as a Backend-as-a-Service (BaaS), meaning it handles server-side operations so you can focus on building your app's frontend.

In this lesson, we'll set up Firebase in a Flutter project and implement basic user authentication.

Firebase Project Setup

First, you need a Firebase project. Go to the Firebase Console and follow these steps:

  • Click 'Add project' and follow the prompts.
  • Once created, click the 'Add app' button (Android or iOS icon).
  • Register your app by providing the package name (Android) or bundle ID (iOS).
  • Download the configuration file: google-services.json for Android, GoogleService-Info.plist for iOS.

Adding Firebase to Flutter

After setting up your project in the Firebase Console, you need to add the necessary dependencies to your Flutter project's pubspec.yaml file.

We'll add firebase_core to initialize Firebase and firebase_auth for authentication.

Then, run flutter pub get in your terminal to fetch the packages.

Initialize Firebase Core

Before using any Firebase services, you must initialize Firebase in your Flutter app, usually in your main() function.

Make sure to call WidgetsFlutterBinding.ensureInitialized() before Firebase.initializeApp() to ensure Flutter's binding is initialized.

The FlutterFire CLI can generate firebase_options.dart for easy platform-specific setup.

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
// import 'firebase_options.dart'; // Generated by FlutterFire CLI

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    // options: DefaultFirebaseOptions.currentPlatform, // Use if generated
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase App',
      home: Scaffold(
        appBar: AppBar(title: Text('Firebase Init')),
        body: Center(child: Text('Firebase initialized!')),
      ),
    );
  }
}

Config File Placement

Place the downloaded configuration files in their correct locations:

  • Android: Move google-services.json into the android/app/ directory of your Flutter project.
  • iOS: Open your Flutter project in Xcode (ios/Runner.xcworkspace), then drag GoogleService-Info.plist into the 'Runner' folder. Make sure to select 'Copy items if needed' and add to all targets.

Email/Password Sign Up

Firebase Authentication supports various sign-in methods. Let's start with Email and Password.

First, enable the 'Email/Password' provider in the Firebase Console under 'Authentication' -> 'Sign-in method'.

Then, use FirebaseAuth.instance.createUserWithEmailAndPassword to register new users.

import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future<User?> signUp(String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      return result.user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // This main is for demonstration of the function logic.
  // In a real app, Firebase.initializeApp() would be called once at app start.
  static void main() async {
    // Simulate Firebase being initialized
    // await Firebase.initializeApp(); 
    
    AuthService auth = AuthService();
    User? user = await auth.signUp("test@example.com", "password123");
    if (user != null) {
      print("Signed up user: ${user.email}");
    } else {
      print("Sign up failed.");
    }
  }
}

Email/Password Sign In

Once a user is registered, they can sign in using their email and password. This is done with the signInWithEmailAndPassword method.

Both sign-up and sign-in methods return a UserCredential object, which contains the User object if successful.

import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future<User?> signIn(String email, String password) async {
    try {
      UserCredential result = await _auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      return result.user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // This main is for demonstration of the function logic.
  // In a real app, Firebase.initializeApp() would be called once at app start.
  static void main() async {
    // Simulate Firebase being initialized
    // await Firebase.initializeApp(); 
    
    AuthService auth = AuthService();
    User? user = await auth.signIn("test@example.com", "password123");
    if (user != null) {
      print("Signed in user: ${user.email}");
    } else {
      print("Sign in failed.");
    }
  }
}

Monitoring Auth State

It's crucial to know if a user is currently signed in or out. Firebase Auth provides a stream called authStateChanges() that emits a new User object whenever the authentication state changes.

This stream can be used with a StreamBuilder widget to dynamically update your UI based on the user's login status.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auth State App',
      home: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          }
          if (snapshot.hasData) {
            return HomeScreen(user: snapshot.data!); // User is signed in
          } else {
            return LoginScreen(); // User is signed out
          }
        },
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  final User user;
  HomeScreen({required this.user});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Welcome')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Logged in as: ${user.email}'),
            ElevatedButton(
              onPressed: () async {
                await FirebaseAuth.instance.signOut();
              },
              child: Text('Sign Out'),
            ),
          ],
        ),
      ),
    );
  }
}

Google Sign-In Setup

Google Sign-In is a popular and user-friendly authentication method. To enable it:

  • In Firebase Console, go to 'Authentication' -> 'Sign-in method' and enable 'Google'.
  • Add the google_sign_in package to your pubspec.yaml.
  • Android: Ensure your SHA-1 fingerprint is registered in Firebase project settings.
  • iOS: Add the Reverse Client ID to your Info.plist file (obtained from GoogleService-Info.plist).

Implementing Google Sign-In

After the setup, you can implement Google Sign-In using the GoogleSignIn package to get user credentials, and then sign in to Firebase with those credentials.

This involves using GoogleSignIn().signIn() and then creating a GoogleAuthProvider.credential to pass to FirebaseAuth.instance.signInWithCredential().

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GoogleAuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<User?> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) return null; // User cancelled the sign-in

      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      UserCredential result = await _auth.signInWithCredential(credential);
      return result.user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // This main is for demonstration of the function logic.
  // In a real app, Firebase.initializeApp() would be called once at app start.
  static void main() async {
    // Simulate Firebase being initialized
    // await Firebase.initializeApp(); 
    
    GoogleAuthService auth = GoogleAuthService();
    User? user = await auth.signInWithGoogle();
    if (user != null) {
      print("Signed in with Google: ${user.email}");
    } else {
      print("Google Sign-In failed or cancelled.");
    }
  }
}

Firebase Auth Quick Check

When should Firebase.initializeApp() be called in a Flutter application to ensure all Firebase services are ready?

Recap & Next Steps

Congratulations! You've learned the essentials of integrating Firebase into your Flutter app and setting up authentication.

We covered:

  • Setting up a Firebase project and adding your Flutter app.
  • Adding Firebase dependencies and initializing Firebase Core.
  • Implementing Email/Password sign-up and sign-in.
  • Monitoring user authentication state changes.
  • Setting up and implementing Google Sign-In.

These are fundamental steps for building secure and interactive Flutter applications with Firebase. Next, you'll explore Cloud Firestore for database integration!

الأسئلة الشائعة

هل درس «إعداد Firebase والمصادقة» مجاني؟

نعم — نص درس «إعداد Firebase والمصادقة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Flutter Mobile Development، انتقل إلى CoddyKit PRO. تتضمن دورة Flutter Mobile Development 4 دروس في المجموع.

ماذا ستتعلم في «إعداد Firebase والمصادقة»؟

أعدّ Firebase في مشروع Flutter لديك ونفّذ مصادقة المستخدم باستخدام البريد الإلكتروني/كلمة المرور وGoogle Sign-In وموفّرين آخرين تتمرن على Flutter Mobile Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Flutter Mobile Development؟

لا تُشترط خبرة سابقة. Flutter Mobile Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «إعداد Firebase والمصادقة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Flutter Mobile Development هذا؟

نعم. كل درس في Flutter Mobile Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. إعداد Firebase والمصادقة
  2. قاعدة بيانات Cloud Firestore
  3. التخزين السحابي والوظائف
  4. Firebase Cloud Messaging والإشعارات
← العودة إلى Flutter Mobile Development