Bird
Raised Fist0
Fluttermobile~20 mins

Firebase Authentication in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Login Screen
This screen allows users to sign in using their email and password with Firebase Authentication.
Target UI
┌───────────────────────────────┐
│           Login Screen         │
├───────────────────────────────┤
│ Email: ______________________ │
│ Password: ___________________ │
│                               │
│ [ Sign In ]                   │
│                               │
│ Don't have an account? Sign Up│
└───────────────────────────────┘
Two TextFields: one for email, one for password
A Sign In button that authenticates with Firebase
Show a loading indicator while signing in
Show error message if sign in fails
A text button to navigate to a Sign Up screen (navigation logic can be a placeholder)
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class LoginScreen extends StatefulWidget {
  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  bool isLoading = false;
  String? errorMessage;

  void signIn() async {
    // TODO: Implement Firebase sign in logic here
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login Screen')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: emailController,
              decoration: InputDecoration(labelText: 'Email'),
              keyboardType: TextInputType.emailAddress,
            ),
            SizedBox(height: 12),
            TextField(
              controller: passwordController,
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            SizedBox(height: 24),
            if (errorMessage != null) ...[
              Text(errorMessage!, style: TextStyle(color: Colors.red)),
              SizedBox(height: 12),
            ],
            isLoading
                ? CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: signIn,
                    child: Text('Sign In'),
                  ),
            SizedBox(height: 24),
            TextButton(
              onPressed: () {
                // TODO: Navigate to Sign Up screen
              },
              child: Text("Don't have an account? Sign Up"),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class LoginScreen extends StatefulWidget {
  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  bool isLoading = false;
  String? errorMessage;

  void signIn() async {
    setState(() {
      isLoading = true;
      errorMessage = null;
    });
    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: emailController.text.trim(),
        password: passwordController.text.trim(),
      );
      // On success, you might navigate to another screen
      // For this example, just clear inputs
      emailController.clear();
      passwordController.clear();
    } on FirebaseAuthException catch (e) {
      setState(() {
        errorMessage = e.message ?? 'Sign in failed';
      });
    } catch (_) {
      setState(() {
        errorMessage = 'An unexpected error occurred';
      });
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login Screen')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: emailController,
              decoration: InputDecoration(labelText: 'Email'),
              keyboardType: TextInputType.emailAddress,
            ),
            SizedBox(height: 12),
            TextField(
              controller: passwordController,
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            SizedBox(height: 24),
            if (errorMessage != null) ...[
              Text(errorMessage!, style: TextStyle(color: Colors.red)),
              SizedBox(height: 12),
            ],
            isLoading
                ? CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: signIn,
                    child: Text('Sign In'),
                  ),
            SizedBox(height: 24),
            TextButton(
              onPressed: () {
                // Placeholder for navigation to Sign Up screen
              },
              child: Text("Don't have an account? Sign Up"),
            ),
          ],
        ),
      ),
    );
  }
}

This solution uses FirebaseAuth's signInWithEmailAndPassword method to authenticate users with their email and password.

We show a loading spinner while waiting for the sign-in process to complete.

If an error occurs, we catch it and display the error message below the input fields in red.

The Sign Up button currently has a placeholder for navigation logic, which you can implement later.

This approach keeps the UI responsive and informs the user about the sign-in status clearly.

Final Result
Completed Screen
┌───────────────────────────────┐
│           Login Screen         │
├───────────────────────────────┤
│ Email: user@example.com       │
│ Password: ********            │
│                               │
│ [ Sign In ]                   │
│                               │
│ Don't have an account? Sign Up│
└───────────────────────────────┘
User enters email and password in text fields
Taps 'Sign In' button to start authentication
Loading spinner appears while signing in
If sign in fails, error message appears in red below inputs
Tapping 'Don't have an account? Sign Up' triggers navigation placeholder
Stretch Goal
Add a 'Forgot Password?' button that sends a password reset email using Firebase Authentication.
💡 Hint
Use FirebaseAuth.instance.sendPasswordResetEmail(email: userEmail) and show a confirmation message.

Practice

(1/5)
1. What is the main purpose of Firebase Authentication in a Flutter app?
easy
A. To send push notifications to users
B. To securely manage user sign-up and login
C. To design the app's user interface
D. To store user data in a database

Solution

  1. Step 1: Understand Firebase Authentication role

    Firebase Authentication helps apps manage user accounts securely.
  2. Step 2: Differentiate from other Firebase services

    It does not store user data or handle UI or notifications.
  3. Final Answer:

    To securely manage user sign-up and login -> Option B
  4. Quick Check:

    Authentication = Secure login [OK]
Hint: Authentication means managing user login securely [OK]
Common Mistakes:
  • Confusing authentication with database storage
  • Thinking it handles UI design
  • Assuming it sends notifications
2. Which Flutter Firebase method is used to sign up a new user with email and password?
easy
A. createUserWithEmailAndPassword
B. signOut
C. signInWithEmailAndPassword
D. sendPasswordResetEmail

Solution

  1. Step 1: Identify sign-up method

    The method to create a new user is createUserWithEmailAndPassword.
  2. Step 2: Differentiate from sign-in and other methods

    signInWithEmailAndPassword is for login, not sign-up.
  3. Final Answer:

    createUserWithEmailAndPassword -> Option A
  4. Quick Check:

    Sign-up method = createUserWithEmailAndPassword [OK]
Hint: Sign-up uses createUserWithEmailAndPassword [OK]
Common Mistakes:
  • Using signInWithEmailAndPassword for sign-up
  • Confusing signOut with sign-up
  • Mixing reset email with sign-up
3. What will the following Flutter code print if the user enters correct email and password?
try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(email: 'user@example.com', password: 'pass123');
  print('Login successful');
} catch (e) {
  print('Login failed');
}
medium
A. No output
B. Login failed
C. Syntax error
D. Login successful

Solution

  1. Step 1: Analyze try block with correct credentials

    Since email and password are correct, signInWithEmailAndPassword succeeds.
  2. Step 2: Check catch block execution

    No error occurs, so catch block is skipped and 'Login successful' prints.
  3. Final Answer:

    Login successful -> Option D
  4. Quick Check:

    Correct login prints success [OK]
Hint: Correct login prints success message [OK]
Common Mistakes:
  • Assuming catch block runs on success
  • Thinking syntax error occurs
  • Ignoring async/await behavior
4. Identify the error in this Flutter Firebase Authentication code snippet:
final user = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
print(user.email);
medium
A. createUserWithEmailAndPassword returns UserCredential, not User
B. Email and password parameters are missing
C. print statement syntax is incorrect
D. Await keyword cannot be used here

Solution

  1. Step 1: Check return type of createUserWithEmailAndPassword

    This method returns a UserCredential object, not a User directly.
  2. Step 2: Access user email correctly

    The email is inside user.user.email, so printing user.email causes error.
  3. Final Answer:

    createUserWithEmailAndPassword returns UserCredential, not User -> Option A
  4. Quick Check:

    Return type is UserCredential [OK]
Hint: Remember createUserWithEmailAndPassword returns UserCredential [OK]
Common Mistakes:
  • Treating UserCredential as User
  • Forgetting to access .user property
  • Misusing await keyword
5. You want to show a friendly error message when login fails due to wrong password. Which Flutter Firebase Authentication code snippet correctly handles this?
try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password);
} catch (e) {
  if (e.code == 'wrong-password') {
    print('Incorrect password. Please try again.');
  } else {
    print('Login error: ' + e.message);
  }
}
hard
A. Correctly checks error code and shows message
B. e.code is not available on exception object
C. Should use on FirebaseAuthException catch instead of generic catch
D. print statements should be replaced with throw

Solution

  1. Step 1: Understand error handling in Firebase Auth

    FirebaseAuthException provides the code property; generic catch (e) may not.
  2. Step 2: Use specific catch for FirebaseAuthException

    Using on FirebaseAuthException catch (e) allows access to e.code safely.
  3. Step 3: Evaluate given code

    Given code uses generic catch, so e.code may cause runtime error.
  4. Final Answer:

    Should use on FirebaseAuthException catch instead of generic catch -> Option C
  5. Quick Check:

    Use FirebaseAuthException catch for error codes [OK]
Hint: Catch FirebaseAuthException to access error codes safely [OK]
Common Mistakes:
  • Using generic catch without exception type
  • Assuming all exceptions have code property
  • Replacing print with throw unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard