0% found this document useful (0 votes)
15 views6 pages

Signup

This document contains code for a Flutter mobile application signup page. It imports necessary packages and defines a Signup widget class with a stateful state. The state class handles form submission which collects user input, validates it, creates a user with Firebase Authentication, saves additional user data to Firestore database, and navigates to another page on success. It builds the signup UI with text fields for name, email, password, and confirm password along with validation.

Uploaded by

saadouli nouha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Signup

This document contains code for a Flutter mobile application signup page. It imports necessary packages and defines a Signup widget class with a stateful state. The state class handles form submission which collects user input, validates it, creates a user with Firebase Authentication, saves additional user data to Firestore database, and navigates to another page on success. It builds the signup UI with text fields for name, email, password, and confirm password along with validation.

Uploaded by

saadouli nouha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

import 'package:cloud_firestore/cloud_firestore.

dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_music1/core/models/user.dart';
import 'package:flutter_music1/core/routes/constants.dart';
import
'package:flutter_music1/core/sevices/firebase_messaging/firebase_messaging.dart';
import 'package:flutter_music1/core/utility/validator.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../../widgets/shared/custum_colors.dart';
import '../../../widgets/shared/form_auth.dart';
import '../../../widgets/shared/snackbarMessaging.dart';

class Signup extends StatefulWidget {


const Signup({super.key});
@override
State<Signup> createState() => _SignupState();
}

class _SignupState extends State<Signup> {


final formKey = GlobalKey<FormState>();
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
final FirebaseMessagingService firebaseMessagingService =
FirebaseMessagingService();
final bool _isProcessing = false;
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _nameController = TextEditingController();
final _confirmPasswordController = TextEditingController();
String mToken = '';
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
_nameController.dispose();
_confirmPasswordController.dispose();
super.dispose();
}
void _trySubmitForm(BuildContext context) {
final bool? isValid = formKey.currentState?.validate();
if (isValid == true) {
debugPrint('Everything looks good!');
_createUserWithEmailAndPassword(context);
}
}

void _createUserWithEmailAndPassword(BuildContext context) async {


try {
final String email = _emailController.text.trim();
final String password = _passwordController.text.trim();
final String fullName = _nameController.text.trim();
final String? token = await firebaseMessagingService.getToken();
// Create the user using Firebase Authentication
UserCredential userCredential = await
_auth.createUserWithEmailAndPassword(email: email, password: password,);
// I can save the email and the password with Firebase Authentication.
// I also save this information with Cloud Firestore.
// But how can I add and save the displayName after registering
await userCredential.user?.updateDisplayName(fullName);
// Store additional user data in Cloud FireStore
await _fireStore
.collection('users')
.doc(userCredential.user!.uid)
.set(UserModel(
id: userCredential.user!.uid,
displayName: fullName,
email: email,
token: token,
isAdmin: false,
).toJson())
.whenComplete(() {
debugPrint('User created successfully!');

snackBarInfo(context: context, message: "User created successfully!");


Navigator.pushReplacementNamed(context, RoutePath.wrapperPage); //??
});/*.onError((error, stackTrace) {
snackBarInfo(
context: context,
message: "Error creating user: $error \n stacktrace : $stackTrace");
});*/
} catch (e) {
// Handle any errors that occurred during registration
snackBarInfo(context: context, message: "Error creating user: $e");
}
}

bool _isSecurePassword = true;


bool _isSecureconfirmPassword = true;

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 25),
child: Icon(
color: Colors.brown.shade800,
Icons.verified_user_rounded,
size: 100,
),
),
Text(
'Register',
style: GoogleFonts.bebasNeue(fontSize: 40,color:
Colors.brown.shade800,),
),
const SizedBox(
height: 20,
),
Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CustomAuthFormField(
icon: const Icon(Icons.person),
controller: _nameController,
hint: "full name",
validate: "other",
validator: (String) {}, /* obscureText: false*/
),
CustomAuthFormField(
icon: const Icon(Icons.email),
controller: _emailController,
hint: "email",
validate: "email",

validator: (String) {},


),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
child: TextFormField(
cursorColor: Colors.orangeAccent,
controller: _passwordController,
validator: "password" != null
? "password" == "email"
? (value) => Validator.validateEmail(
value: _confirmPasswordController.text)
: "password" == "password"
? (value) => Validator.validatePassword(
_confirmPasswordController.text)
: "password" == "matchPassword"
? (value) =>
Validator.validatePasswordMatch(
_confirmPasswordController
.text,
_passwordController.text)
: (value) => Validator.validateField(
value: _confirmPasswordController
.text)
: null,
decoration: InputDecoration(

errorStyle: const TextStyle(


color: Colors.deepOrange,
),
prefixIcon: const Icon(
Icons.lock,
),
suffixIcon: togglePassword(),
hintText: "password",
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.white),
borderRadius: BorderRadius.circular(10),
),
focusedBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.orangeAccent),
borderRadius: BorderRadius.circular(12),
),
prefixIconColor: MaterialStateColor.resolveWith(
(states) =>
states.contains(MaterialState.focused)
? Colors.orangeAccent
: Colors.black54),
suffixIconColor: MaterialStateColor.resolveWith(
(states) =>
states.contains(MaterialState.focused)
? Colors.orangeAccent
: Colors.black54),
filled: true,
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: const BorderSide(
color: Colors.deepOrange,
width: 1,
),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: const BorderSide(
color: Colors.orangeAccent,
width: 1,
),
),

),
obscureText: _isSecurePassword,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20,
vertical: 10),
child: TextFormField(
controller: _confirmPasswordController,
validator: "matchPassword" != null
? "matchPassword" == "email"
? (value) => Validator.validateEmail(
value: _confirmPasswordController.text)
: "matchPassword" == "password"
? (value) => Validator.validatePassword(
_confirmPasswordController.text)
: "matchPassword" == "matchPassword"
? (value) =>
Validator.validatePasswordMatch(
_confirmPasswordController
.text,
_passwordController.text)
: (value) => Validator.validateField(
value: _confirmPasswordController
.text)
: null,
decoration: InputDecoration(
errorStyle: const TextStyle(
color: Colors.deepOrange,
),
prefixIcon: const Icon(
Icons.lock,
),
suffixIcon: toggleconfirmPassword(),
hintText: "confirm password",
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.white),
borderRadius: BorderRadius.circular(10),
),
focusedBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.orangeAccent),
borderRadius: BorderRadius.circular(12),
),
prefixIconColor: MaterialStateColor.resolveWith(
(states) =>
states.contains(MaterialState.focused)
? Colors.orangeAccent
: Colors.black54),
suffixIconColor: MaterialStateColor.resolveWith(
(states) =>
states.contains(MaterialState.focused)
? Colors.orangeAccent
: Colors.black54),
filled: true,
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: const BorderSide(
color: Colors.red,
width: 1,
),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: const BorderSide(
color: Colors.orangeAccent,
width: 1,
),
),
),
obscureText: _isSecureconfirmPassword,
),
)
]),
),
// dropDownMenuProfileType(),
_isProcessing
? Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
CustomColors.firebaseOrange,
),
),
),
)
: Padding(
padding:const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
child: GestureDetector(

onTap: () => _trySubmitForm(context),


child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.circular(12)),
child: const Center(
child: Text(
'Sign Up',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
),
),
),
],
),
),
),
);
}

Widget toggleconfirmPassword() {
return IconButton(
onPressed: () {
setState(() {
_isSecureconfirmPassword = !_isSecureconfirmPassword;
});
},
icon: _isSecureconfirmPassword
? const Icon(Icons.visibility_off)

: const Icon(Icons.visibility)
);
}

Widget togglePassword() {
return IconButton(
onPressed: () {
setState(() {
_isSecurePassword = !_isSecurePassword;
});
},
icon: _isSecurePassword
? const Icon(Icons.visibility_off)

: const Icon(Icons.visibility)
);
}

You might also like