Authenticate with Firebase Using Email and Password
To enable email and password authentication in your News App, follow these steps:
-
Open your Firebase console.
-
Navigate to Authentication and select the Sign-in method tab.
-
Find Email/Password authentication method and enable it. You should enable both "Allow users to sign in with their email and password" and "Email link (passwordless sign-in)" options.
After pressing the save button, email authentication will be enabled in your app.
-
You can customize the sender name and subject for verify email and reset password messages:
With these settings in place, users will be able to register and log into your News App using their email and password.
Configure Your App
- Make sure you have added the Firebase Auth dependency in
pubspec.yaml
:
dependencies:
firebase_auth: ^latest_version
-
Run
flutter pub get
to install the dependency -
Initialize Firebase in your app:
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Implementation Example
Here's a simple example of how to implement email/password authentication in your app:
// Sign up a new user
Future<UserCredential> signUp(String email, String password) async {
try {
return await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
} catch (e) {
print('Error during sign up: $e');
rethrow;
}
}
// Sign in an existing user
Future<UserCredential> signIn(String email, String password) async {
try {
return await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
} catch (e) {
print('Error during sign in: $e');
rethrow;
}
}
Always handle authentication errors properly and show appropriate error messages to users.