register functionality added

This commit is contained in:
venbaittech 2024-11-14 10:15:20 +05:30
parent 1025ef60a1
commit acaa9f046c
3 changed files with 130 additions and 65 deletions

View File

@ -3,7 +3,7 @@ import 'dart:convert';
import 'package:pocketbase/pocketbase.dart';
abstract class PocketBaseService {
static const _host = 'https://pocket.fcsc.gov.ae';
static const _host = 'https://pb.venbait.in';
// static const _host = 'http://127.0.0.1:8090';
static final _pb = PocketBase(_host);
static final users = _pb.collection('users');

View File

@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
@ -11,6 +12,9 @@ import 'package:pocketbase/pocketbase.dart';
import 'changepassword.dart';
class ProfileScreen extends StatefulWidget {
final String userId; // Add this field to hold the user ID
const ProfileScreen({Key? key, required this.userId}) : super(key: key);
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
@ -42,10 +46,12 @@ class _ProfileScreenState extends State<ProfileScreen> {
// Regular expression to validate Full Name (no special characters)
final RegExp _nameRegExp = RegExp(r"^[a-zA-Z\s]+$");
late Future<RecordModel> userDetails;
@override
void initState() {
super.initState();
print(widget.userId);
_fetchUserData(); // Call the function to fetch user data
}
@ -56,32 +62,24 @@ class _ProfileScreenState extends State<ProfileScreen> {
super.dispose();
}
void _fetchUserData() async {
Future<void> _fetchUserData() async {
try {
final userId = 'tsgehyvgy6owypj';
final adminAuth = await _pb.admins
.authWithPassword('pb@venbainfotech.com', 'pb@venbainfotech.com');
final adminToken = adminAuth.token;
final response = await http.get(
Uri.parse(
'https://pb.venbait.in/api/collections/users/records/$userId'),
final userDetailsResponse = await _pb.collection('users').getOne(
widget.userId,
headers: {
'Authorization': 'Bearer $adminToken', // Add token to header
'Content-Type': 'application/json',
'Authorization': 'Bearer $adminToken',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
setState(() {
_usernameController.text = data['username'];
_emailController.text = data['email'];
});
} else {
print('Failed to fetch user data: ${response.body}');
}
} catch (error) {
print('Failed to fetch user data: $error');
print('userDetails: $userDetailsResponse');
setState(() {
_usernameController.text = userDetailsResponse.data['username'] ?? '';
_emailController.text = userDetailsResponse.data['email'] ?? '';
});
} catch (e) {
print('Error fetching user details: $e');
}
}
@ -160,7 +158,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
if (result == true) {
if (_formKey.currentState?.validate() ?? false) {
try {
String userID = 'tsgehyvgy6owypj';
String userID = widget.userId;
// Retrieve data from text fields and other inputs
String fullName = _fullNameController.text;
// String username = 'users55538';
@ -208,7 +206,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
if (response.statusCode == 200) {
print(response.statusCode);
_resetFormFields();
Navigator.pushNamed(context, 'home');
// Navigator.pushNamed(context, 'home');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Profile updated successfully!")));
} else {
@ -379,7 +377,10 @@ class _ProfileScreenState extends State<ProfileScreen> {
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
counterText: '',
),
maxLength: 40, // Set the maximum length to 20 characters
maxLengthEnforcement: MaxLengthEnforcement.enforced,
),
SizedBox(height: 10),
Row(
@ -526,7 +527,6 @@ class _ProfileScreenState extends State<ProfileScreen> {
),
],
),
SizedBox(height: 20),
Center(
child: GestureDetector(
@ -548,14 +548,14 @@ class _ProfileScreenState extends State<ProfileScreen> {
SizedBox(height: 20),
ElevatedButton.icon(
onPressed: () {
if((_formKey.currentState?.validate() ?? false) && (isChecked)){
if ((_formKey.currentState?.validate() ?? false) &&
(isChecked)) {
_formKey.currentState?.save();
showConfirmationDialog(context);
}
else {
} else {
setState(() {
showError = !isChecked; // Show error if the checkbox is not checked
showError =
!isChecked; // Show error if the checkbox is not checked
});
}
// if ((_formKey.currentState?.validate() ?? false) && (isChecked)) {
@ -571,10 +571,10 @@ class _ProfileScreenState extends State<ProfileScreen> {
// showError = !isChecked; // Show error if the checkbox is not checked
// });
// ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(content: Text('Please accept the terms and conditions.',style: TextStyle(color: Colors.white),)),
// );
//}
// ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(content: Text('Please accept the terms and conditions.',style: TextStyle(color: Colors.white),)),
// );
//}
//}
},
icon: Icon(

View File

@ -1,6 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pocketbase/pocketbase.dart';
import 'package:uae_stat/presentation/Screens/profilepage.dart';
import '../../infrastructure/services/pocketbase_service.dart';
class RegisterScreen extends StatefulWidget {
@override
_RegisterScreenState createState() => _RegisterScreenState();
@ -8,13 +12,30 @@ class RegisterScreen extends StatefulWidget {
class _RegisterScreenState extends State<RegisterScreen> {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
bool _obscureConfirmPassword = true;
bool isChecked = false;
bool showError = false;
String? _password;
final pb = PocketBase('https://pb.venbait.in');
@override
void initState() {
super.initState();
}
@override
void dispose() {
_usernameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
String? _validateUsername(String? value) {
if (value == null || value.isEmpty) {
return 'Required';
@ -52,6 +73,53 @@ class _RegisterScreenState extends State<RegisterScreen> {
return null;
}
Future<void> _registerUser() async {
if (_formKey.currentState?.validate() ?? false) {
if (isChecked) {
try {
// Create user in PocketBase
final response = await pb.collection('users').create(body: {
'username': _usernameController.text,
'email': _emailController.text,
'password': _passwordController.text,
'passwordConfirm': _passwordController
.text, // PocketBase requires password confirmation
});
if (response.id != null) {
// Request email verification
PocketBaseService.users.requestVerification(_emailController.text);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Registration Successed')),
);
// Navigate to ProfileScreen after successful registration
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => ProfileScreen(userId: response.id)),
);
} else {
throw Exception('User registration failed: missing user ID');
}
} catch (e) {
// Handle registration error
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Registration failed: $e')),
);
}
} else {
setState(() {
showError = true; // Show error if checkbox is not checked
});
}
} else {
setState(() {
showError = !isChecked; // Show error if the checkbox is not checked
});
}
}
@override
Widget build(BuildContext context) {
double screenheight = MediaQuery.of(context).size.height;
@ -75,6 +143,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
Text('Please enter your details'),
SizedBox(height: 20),
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
hintText: 'Username',
prefixIcon: Icon(
@ -82,11 +151,15 @@ class _RegisterScreenState extends State<RegisterScreen> {
color: Colors.blue,
),
border: OutlineInputBorder(),
counterText: '',
),
validator: _validateUsername,
maxLength: 40, // Set the maximum length to 20 characters
maxLengthEnforcement: MaxLengthEnforcement.enforced,
),
SizedBox(height: 15),
TextFormField(
controller: _emailController,
decoration: InputDecoration(
hintText: 'Enter your email',
prefixIcon: Icon(
@ -99,6 +172,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
),
SizedBox(height: 15),
TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
decoration: InputDecoration(
hintText: 'Enter your password',
@ -203,23 +277,12 @@ class _RegisterScreenState extends State<RegisterScreen> {
),
SizedBox(height: 20),
SizedBox(
width: screenwidth/1.3,
width: screenwidth / 1.3,
child: ElevatedButton(
onPressed: () {
if ((_formKey.currentState?.validate() ?? false) && isChecked) {
// Proceed with registration if form is valid and checkbox is checked
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfileScreen()),
);
} else {
setState(() {
showError = !isChecked; // Show error if the checkbox is not checked
});
}
},
onPressed: _registerUser,
style: ElevatedButton.styleFrom(
backgroundColor: Color(0xFFA7887A), // Brownish color for Register
backgroundColor:
Color(0xFFA7887A), // Brownish color for Register
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
@ -244,13 +307,14 @@ class _RegisterScreenState extends State<RegisterScreen> {
),
SizedBox(height: 10),
SizedBox(
width: screenwidth/1.3,
width: screenwidth / 1.3,
child: ElevatedButton(
onPressed: () {
// Add your login logic here
},
style: ElevatedButton.styleFrom(
backgroundColor: Color(0xFF82AFCB), // Blueish color for Login
backgroundColor:
Color(0xFF82AFCB), // Blueish color for Login
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
@ -268,18 +332,22 @@ class _RegisterScreenState extends State<RegisterScreen> {
),
),
),
SizedBox(height: 10,),
Center(
child: Container(
height: screenheight/8,
width: screenwidth/2,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/splash_screen/logo.png"), // Background image asset
fit: BoxFit.fill,
),
),
))],
SizedBox(
height: 10,
),
Center(
child: Container(
height: screenheight / 8,
width: screenwidth / 2,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
"assets/splash_screen/logo.png"), // Background image asset
fit: BoxFit.fill,
),
),
))
],
),
),
),
@ -287,6 +355,3 @@ class _RegisterScreenState extends State<RegisterScreen> {
);
}
}