Saturday, June 3, 2023

Build Secure and Easy-to-Use Flutter Firebase Authentication Application



Sure! Here's an example of a Flutter application that demonstrates Firebase authentication using the FirebaseAuth package. Please note that you'll need to set up Firebase in your Flutter project before running this code.

First, add the firebase_auth package to your pubspec.yaml file:

dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.0
firebase_auth: ^1.0.1

Then, import the necessary packages in your Dart file:

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


Next, initialize Firebase in the main() method:

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

Create the MyApp widget, which serves as the entry point for your application:

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Authentication',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(),
);
}
}

 
Create the LoginPage widget where users can sign in or register:
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();

Future<void> _signInWithEmailAndPassword() async {
try {
final String email = _emailController.text.trim();
final String password = _passwordController.text.trim();
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
// User successfully signed in
print('Signed in: ${userCredential.user}');
} catch (e) {
// Handle sign-in errors
print('Sign-in error: $e');
}
}


Future<void> _registerWithEmailAndPassword() async {
try {
final String email = _emailController.text.trim();
final String password = _passwordController.text.trim();
UserCredential userCredential =
await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
// User successfully registered
print('Registered: ${userCredential.user}');
} catch (e) {
// Handle registration errors
print('Registration error: $e');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Login')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
SizedBox(height: 16.0),
ElevatedButton(
onPressed: _signInWithEmailAndPassword,
child: Text('Sign In'),
),
ElevatedButton(
onPressed: _registerWithEmailAndPassword,
child: Text('Register'),
),
],
),
),
);
}
}

 

This code provides a basic login page with email and password text fields. The user can sign in with existing credentials or register a new account. The Firebase authentication methods _signInWithEmailAndPassword() and _registerWithEmailAndPassword() handle the respective operations.

Remember to set up Firebase in your Flutter project and enable the appropriate sign-in methods in the Firebase console. Additionally, handle error cases and customize the UI as needed to fit your application's requirements

No comments:

Post a Comment

Enhancing Flutter Apps with BLoC State Management and REST APIs for Optimal Performance

 Develop a powerful Flutter app utilizing BLoC state management and REST APIs to enhance functionality and performance. Flutter app using th...