feat: Implement initial authentication, multi-environment support, and core app infrastructure.

This commit is contained in:
pradeepkumar
2026-02-23 19:23:30 +05:30
parent 0f07a16132
commit 4f8ad7fe49
55 changed files with 3836 additions and 118 deletions

View File

@@ -0,0 +1,16 @@
import 'package:flutter_dotenv/flutter_dotenv.dart';
enum Flavor { local, demo, dev }
class AppConfig {
static late Flavor flavor;
static String get envFileName => '.env.${flavor.name}';
static Future<void> init(Flavor f) async {
flavor = f;
await dotenv.load(fileName: envFileName);
}
static String get apiBaseUrl => dotenv.env['API_BASE_URL'] ?? '';
}

View File

@@ -0,0 +1,13 @@
class ApiConstants {
ApiConstants._();
static const String authRegister = '/auth/register';
static const String authLogin = '/auth/login';
static const String authForgotPassword = '/auth/forgot-password';
static const String authResetPassword = '/auth/reset-password';
static const String authVerifyEmail = '/auth/verify-email';
static const String authResendVerification = '/auth/resend-verification';
static const String authMe = '/auth/me';
static const String authRefresh = '/auth/refresh';
static const String authLogout = '/auth/logout';
}

View File

@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
class AppColors {
AppColors._();
static const Color primaryDark = Color(0xFF00293D);
static const Color accentOrange = Color(0xFFE58625);
static const Color accentOrangeHover = Color(0xFFD47A1F);
static const Color gradientStart = Color(0xFFC4D9D4);
static const Color gradientEnd = Color(0xFFF0F5FC);
static const Color inputFill = Color(0xFFF0F5FC);
static const Color white = Color(0xFFFFFFFF);
static const Color error = Color(0xFFDC2626);
static const Color errorBg = Color(0xFFFEF2F2);
static const Color errorBorder = Color(0xFFFECACA);
static const Color success = Color(0xFF22C55E);
static const Color divider = Color(0x3300293D); // 20% opacity
static const Color hintText = Color(0x9900293D); // 60% opacity
static const Color subtleText = Color(0x7000293D); // ~44% opacity
}

View File

@@ -0,0 +1,92 @@
import 'package:dio/dio.dart';
import 'package:real_estate_mobile/config/app_config.dart';
import 'package:real_estate_mobile/core/network/api_exceptions.dart';
import 'package:real_estate_mobile/core/storage/secure_storage.dart';
class ApiClient {
static ApiClient? _instance;
late final Dio _dio;
ApiClient._() {
_dio = Dio(
BaseOptions(
baseUrl: AppConfig.apiBaseUrl,
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
),
);
_dio.interceptors.addAll([
_authInterceptor(),
_errorInterceptor(),
]);
}
static ApiClient get instance {
_instance ??= ApiClient._();
return _instance!;
}
Dio get dio => _dio;
InterceptorsWrapper _authInterceptor() {
return InterceptorsWrapper(
onRequest: (options, handler) async {
final token = await SecureStorage.getAccessToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
},
);
}
InterceptorsWrapper _errorInterceptor() {
return InterceptorsWrapper(
onError: (error, handler) {
final response = error.response;
if (response != null) {
final data = response.data;
if (data is Map<String, dynamic>) {
final message = data['message'] is List
? (data['message'] as List).join(', ')
: data['message']?.toString() ?? 'An error occurred';
final errors = (data['errors'] as List<dynamic>?)
?.map((e) => FieldError.fromJson(e as Map<String, dynamic>))
.toList() ??
[];
handler.reject(
DioException(
requestOptions: error.requestOptions,
response: error.response,
error: ApiException(
message: message,
statusCode: response.statusCode,
fieldErrors: errors,
),
),
);
return;
}
}
handler.reject(
DioException(
requestOptions: error.requestOptions,
response: error.response,
error: ApiException(
message: error.message ?? 'Network error occurred',
statusCode: response?.statusCode,
),
),
);
},
);
}
}

View File

@@ -0,0 +1,31 @@
class ApiException implements Exception {
final String message;
final int? statusCode;
final List<FieldError> fieldErrors;
const ApiException({
required this.message,
this.statusCode,
this.fieldErrors = const [],
});
@override
String toString() => 'ApiException: $message (status: $statusCode)';
}
class FieldError {
final String field;
final List<String> errors;
const FieldError({required this.field, required this.errors});
factory FieldError.fromJson(Map<String, dynamic> json) {
return FieldError(
field: json['field'] as String? ?? '',
errors: (json['errors'] as List<dynamic>?)
?.map((e) => e.toString())
.toList() ??
[],
);
}
}

View File

@@ -0,0 +1,33 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorage {
static const _storage = FlutterSecureStorage();
static const _accessTokenKey = 'access_token';
static const _refreshTokenKey = 'refresh_token';
static Future<void> saveTokens({
required String accessToken,
required String refreshToken,
}) async {
await Future.wait([
_storage.write(key: _accessTokenKey, value: accessToken),
_storage.write(key: _refreshTokenKey, value: refreshToken),
]);
}
static Future<String?> getAccessToken() async {
return _storage.read(key: _accessTokenKey);
}
static Future<String?> getRefreshToken() async {
return _storage.read(key: _refreshTokenKey);
}
static Future<void> clearTokens() async {
await Future.wait([
_storage.delete(key: _accessTokenKey),
_storage.delete(key: _refreshTokenKey),
]);
}
}

View File

@@ -0,0 +1,118 @@
import 'package:flutter/material.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
class AppTheme {
AppTheme._();
static ThemeData get light {
return ThemeData(
useMaterial3: true,
fontFamily: 'Fractul',
scaffoldBackgroundColor: AppColors.white,
colorScheme: ColorScheme.fromSeed(
seedColor: AppColors.primaryDark,
primary: AppColors.primaryDark,
secondary: AppColors.accentOrange,
surface: AppColors.white,
error: AppColors.error,
),
textTheme: const TextTheme(
headlineLarge: TextStyle(
fontFamily: 'Fractul',
fontSize: 30,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
headlineMedium: TextStyle(
fontFamily: 'Fractul',
fontSize: 25,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
titleMedium: TextStyle(
fontFamily: 'Fractul',
fontSize: 16,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
bodyMedium: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark,
),
bodySmall: TextStyle(
fontFamily: 'Fractul',
fontSize: 12,
fontWeight: FontWeight.w300,
color: AppColors.hintText,
),
labelLarge: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w700,
color: AppColors.primaryDark,
),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: AppColors.inputFill,
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 20,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: const BorderSide(
color: AppColors.primaryDark,
width: 1.5,
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: const BorderSide(
color: AppColors.error,
width: 1.5,
),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: const BorderSide(
color: AppColors.error,
width: 1.5,
),
),
hintStyle: const TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark,
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.accentOrange,
foregroundColor: AppColors.primaryDark,
elevation: 0,
padding: const EdgeInsets.symmetric(vertical: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
textStyle: const TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w700,
),
),
),
);
}
}

View File

@@ -0,0 +1,81 @@
import 'package:dio/dio.dart';
import 'package:real_estate_mobile/core/constants/api_constants.dart';
import 'package:real_estate_mobile/core/network/api_client.dart';
import 'package:real_estate_mobile/core/network/api_exceptions.dart';
import 'package:real_estate_mobile/core/storage/secure_storage.dart';
import 'package:real_estate_mobile/features/auth/data/models/auth_response.dart';
import 'package:real_estate_mobile/features/auth/data/models/register_request.dart';
import 'package:real_estate_mobile/features/auth/data/models/user_model.dart';
class AuthRepository {
final Dio _dio = ApiClient.instance.dio;
Future<Map<String, dynamic>> login({
required String email,
required String password,
}) async {
try {
final response = await _dio.post(
ApiConstants.authLogin,
data: {'email': email, 'password': password},
);
final data = response.data['data'] as Map<String, dynamic>;
// Check if 2FA is required
if (data['requiresTwoFactor'] == true) {
return {
'requiresTwoFactor': true,
'tempToken': data['tempToken'],
};
}
final authResponse = AuthResponse.fromJson(data);
await SecureStorage.saveTokens(
accessToken: authResponse.accessToken,
refreshToken: authResponse.refreshToken,
);
return {
'requiresTwoFactor': false,
'user': authResponse.user,
};
} on DioException catch (e) {
if (e.error is ApiException) {
throw e.error as ApiException;
}
throw ApiException(
message: e.message ?? 'Login failed',
statusCode: e.response?.statusCode,
);
}
}
Future<UserModel> register(RegisterRequest request) async {
try {
final response = await _dio.post(
ApiConstants.authRegister,
data: request.toJson(),
);
final data = response.data['data'] as Map<String, dynamic>;
final authResponse = AuthResponse.fromJson(data);
await SecureStorage.saveTokens(
accessToken: authResponse.accessToken,
refreshToken: authResponse.refreshToken,
);
return authResponse.user;
} on DioException catch (e) {
if (e.error is ApiException) {
throw e.error as ApiException;
}
throw ApiException(
message: e.message ?? 'Registration failed',
statusCode: e.response?.statusCode,
);
}
}
}

View File

@@ -0,0 +1,17 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:real_estate_mobile/features/auth/data/models/user_model.dart';
part 'auth_response.freezed.dart';
part 'auth_response.g.dart';
@freezed
abstract class AuthResponse with _$AuthResponse {
const factory AuthResponse({
required UserModel user,
required String accessToken,
required String refreshToken,
}) = _AuthResponse;
factory AuthResponse.fromJson(Map<String, dynamic> json) =>
_$AuthResponseFromJson(json);
}

View File

@@ -0,0 +1,301 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'auth_response.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$AuthResponse {
UserModel get user; String get accessToken; String get refreshToken;
/// Create a copy of AuthResponse
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$AuthResponseCopyWith<AuthResponse> get copyWith => _$AuthResponseCopyWithImpl<AuthResponse>(this as AuthResponse, _$identity);
/// Serializes this AuthResponse to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is AuthResponse&&(identical(other.user, user) || other.user == user)&&(identical(other.accessToken, accessToken) || other.accessToken == accessToken)&&(identical(other.refreshToken, refreshToken) || other.refreshToken == refreshToken));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,user,accessToken,refreshToken);
@override
String toString() {
return 'AuthResponse(user: $user, accessToken: $accessToken, refreshToken: $refreshToken)';
}
}
/// @nodoc
abstract mixin class $AuthResponseCopyWith<$Res> {
factory $AuthResponseCopyWith(AuthResponse value, $Res Function(AuthResponse) _then) = _$AuthResponseCopyWithImpl;
@useResult
$Res call({
UserModel user, String accessToken, String refreshToken
});
$UserModelCopyWith<$Res> get user;
}
/// @nodoc
class _$AuthResponseCopyWithImpl<$Res>
implements $AuthResponseCopyWith<$Res> {
_$AuthResponseCopyWithImpl(this._self, this._then);
final AuthResponse _self;
final $Res Function(AuthResponse) _then;
/// Create a copy of AuthResponse
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? user = null,Object? accessToken = null,Object? refreshToken = null,}) {
return _then(_self.copyWith(
user: null == user ? _self.user : user // ignore: cast_nullable_to_non_nullable
as UserModel,accessToken: null == accessToken ? _self.accessToken : accessToken // ignore: cast_nullable_to_non_nullable
as String,refreshToken: null == refreshToken ? _self.refreshToken : refreshToken // ignore: cast_nullable_to_non_nullable
as String,
));
}
/// Create a copy of AuthResponse
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$UserModelCopyWith<$Res> get user {
return $UserModelCopyWith<$Res>(_self.user, (value) {
return _then(_self.copyWith(user: value));
});
}
}
/// Adds pattern-matching-related methods to [AuthResponse].
extension AuthResponsePatterns on AuthResponse {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _AuthResponse value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _AuthResponse() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _AuthResponse value) $default,){
final _that = this;
switch (_that) {
case _AuthResponse():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _AuthResponse value)? $default,){
final _that = this;
switch (_that) {
case _AuthResponse() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( UserModel user, String accessToken, String refreshToken)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _AuthResponse() when $default != null:
return $default(_that.user,_that.accessToken,_that.refreshToken);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( UserModel user, String accessToken, String refreshToken) $default,) {final _that = this;
switch (_that) {
case _AuthResponse():
return $default(_that.user,_that.accessToken,_that.refreshToken);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( UserModel user, String accessToken, String refreshToken)? $default,) {final _that = this;
switch (_that) {
case _AuthResponse() when $default != null:
return $default(_that.user,_that.accessToken,_that.refreshToken);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _AuthResponse implements AuthResponse {
const _AuthResponse({required this.user, required this.accessToken, required this.refreshToken});
factory _AuthResponse.fromJson(Map<String, dynamic> json) => _$AuthResponseFromJson(json);
@override final UserModel user;
@override final String accessToken;
@override final String refreshToken;
/// Create a copy of AuthResponse
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$AuthResponseCopyWith<_AuthResponse> get copyWith => __$AuthResponseCopyWithImpl<_AuthResponse>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$AuthResponseToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AuthResponse&&(identical(other.user, user) || other.user == user)&&(identical(other.accessToken, accessToken) || other.accessToken == accessToken)&&(identical(other.refreshToken, refreshToken) || other.refreshToken == refreshToken));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,user,accessToken,refreshToken);
@override
String toString() {
return 'AuthResponse(user: $user, accessToken: $accessToken, refreshToken: $refreshToken)';
}
}
/// @nodoc
abstract mixin class _$AuthResponseCopyWith<$Res> implements $AuthResponseCopyWith<$Res> {
factory _$AuthResponseCopyWith(_AuthResponse value, $Res Function(_AuthResponse) _then) = __$AuthResponseCopyWithImpl;
@override @useResult
$Res call({
UserModel user, String accessToken, String refreshToken
});
@override $UserModelCopyWith<$Res> get user;
}
/// @nodoc
class __$AuthResponseCopyWithImpl<$Res>
implements _$AuthResponseCopyWith<$Res> {
__$AuthResponseCopyWithImpl(this._self, this._then);
final _AuthResponse _self;
final $Res Function(_AuthResponse) _then;
/// Create a copy of AuthResponse
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? user = null,Object? accessToken = null,Object? refreshToken = null,}) {
return _then(_AuthResponse(
user: null == user ? _self.user : user // ignore: cast_nullable_to_non_nullable
as UserModel,accessToken: null == accessToken ? _self.accessToken : accessToken // ignore: cast_nullable_to_non_nullable
as String,refreshToken: null == refreshToken ? _self.refreshToken : refreshToken // ignore: cast_nullable_to_non_nullable
as String,
));
}
/// Create a copy of AuthResponse
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$UserModelCopyWith<$Res> get user {
return $UserModelCopyWith<$Res>(_self.user, (value) {
return _then(_self.copyWith(user: value));
});
}
}
// dart format on

View File

@@ -0,0 +1,21 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'auth_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_AuthResponse _$AuthResponseFromJson(Map<String, dynamic> json) =>
_AuthResponse(
user: UserModel.fromJson(json['user'] as Map<String, dynamic>),
accessToken: json['accessToken'] as String,
refreshToken: json['refreshToken'] as String,
);
Map<String, dynamic> _$AuthResponseToJson(_AuthResponse instance) =>
<String, dynamic>{
'user': instance.user,
'accessToken': instance.accessToken,
'refreshToken': instance.refreshToken,
};

View File

@@ -0,0 +1,18 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'register_request.freezed.dart';
part 'register_request.g.dart';
@freezed
abstract class RegisterRequest with _$RegisterRequest {
const factory RegisterRequest({
required String email,
required String password,
required String role,
String? firstName,
String? lastName,
}) = _RegisterRequest;
factory RegisterRequest.fromJson(Map<String, dynamic> json) =>
_$RegisterRequestFromJson(json);
}

View File

@@ -0,0 +1,289 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'register_request.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$RegisterRequest {
String get email; String get password; String get role; String? get firstName; String? get lastName;
/// Create a copy of RegisterRequest
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$RegisterRequestCopyWith<RegisterRequest> get copyWith => _$RegisterRequestCopyWithImpl<RegisterRequest>(this as RegisterRequest, _$identity);
/// Serializes this RegisterRequest to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is RegisterRequest&&(identical(other.email, email) || other.email == email)&&(identical(other.password, password) || other.password == password)&&(identical(other.role, role) || other.role == role)&&(identical(other.firstName, firstName) || other.firstName == firstName)&&(identical(other.lastName, lastName) || other.lastName == lastName));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,email,password,role,firstName,lastName);
@override
String toString() {
return 'RegisterRequest(email: $email, password: $password, role: $role, firstName: $firstName, lastName: $lastName)';
}
}
/// @nodoc
abstract mixin class $RegisterRequestCopyWith<$Res> {
factory $RegisterRequestCopyWith(RegisterRequest value, $Res Function(RegisterRequest) _then) = _$RegisterRequestCopyWithImpl;
@useResult
$Res call({
String email, String password, String role, String? firstName, String? lastName
});
}
/// @nodoc
class _$RegisterRequestCopyWithImpl<$Res>
implements $RegisterRequestCopyWith<$Res> {
_$RegisterRequestCopyWithImpl(this._self, this._then);
final RegisterRequest _self;
final $Res Function(RegisterRequest) _then;
/// Create a copy of RegisterRequest
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? email = null,Object? password = null,Object? role = null,Object? firstName = freezed,Object? lastName = freezed,}) {
return _then(_self.copyWith(
email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable
as String,password: null == password ? _self.password : password // ignore: cast_nullable_to_non_nullable
as String,role: null == role ? _self.role : role // ignore: cast_nullable_to_non_nullable
as String,firstName: freezed == firstName ? _self.firstName : firstName // ignore: cast_nullable_to_non_nullable
as String?,lastName: freezed == lastName ? _self.lastName : lastName // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// Adds pattern-matching-related methods to [RegisterRequest].
extension RegisterRequestPatterns on RegisterRequest {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _RegisterRequest value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _RegisterRequest() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _RegisterRequest value) $default,){
final _that = this;
switch (_that) {
case _RegisterRequest():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _RegisterRequest value)? $default,){
final _that = this;
switch (_that) {
case _RegisterRequest() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String email, String password, String role, String? firstName, String? lastName)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _RegisterRequest() when $default != null:
return $default(_that.email,_that.password,_that.role,_that.firstName,_that.lastName);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String email, String password, String role, String? firstName, String? lastName) $default,) {final _that = this;
switch (_that) {
case _RegisterRequest():
return $default(_that.email,_that.password,_that.role,_that.firstName,_that.lastName);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String email, String password, String role, String? firstName, String? lastName)? $default,) {final _that = this;
switch (_that) {
case _RegisterRequest() when $default != null:
return $default(_that.email,_that.password,_that.role,_that.firstName,_that.lastName);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _RegisterRequest implements RegisterRequest {
const _RegisterRequest({required this.email, required this.password, required this.role, this.firstName, this.lastName});
factory _RegisterRequest.fromJson(Map<String, dynamic> json) => _$RegisterRequestFromJson(json);
@override final String email;
@override final String password;
@override final String role;
@override final String? firstName;
@override final String? lastName;
/// Create a copy of RegisterRequest
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$RegisterRequestCopyWith<_RegisterRequest> get copyWith => __$RegisterRequestCopyWithImpl<_RegisterRequest>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$RegisterRequestToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _RegisterRequest&&(identical(other.email, email) || other.email == email)&&(identical(other.password, password) || other.password == password)&&(identical(other.role, role) || other.role == role)&&(identical(other.firstName, firstName) || other.firstName == firstName)&&(identical(other.lastName, lastName) || other.lastName == lastName));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,email,password,role,firstName,lastName);
@override
String toString() {
return 'RegisterRequest(email: $email, password: $password, role: $role, firstName: $firstName, lastName: $lastName)';
}
}
/// @nodoc
abstract mixin class _$RegisterRequestCopyWith<$Res> implements $RegisterRequestCopyWith<$Res> {
factory _$RegisterRequestCopyWith(_RegisterRequest value, $Res Function(_RegisterRequest) _then) = __$RegisterRequestCopyWithImpl;
@override @useResult
$Res call({
String email, String password, String role, String? firstName, String? lastName
});
}
/// @nodoc
class __$RegisterRequestCopyWithImpl<$Res>
implements _$RegisterRequestCopyWith<$Res> {
__$RegisterRequestCopyWithImpl(this._self, this._then);
final _RegisterRequest _self;
final $Res Function(_RegisterRequest) _then;
/// Create a copy of RegisterRequest
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? email = null,Object? password = null,Object? role = null,Object? firstName = freezed,Object? lastName = freezed,}) {
return _then(_RegisterRequest(
email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable
as String,password: null == password ? _self.password : password // ignore: cast_nullable_to_non_nullable
as String,role: null == role ? _self.role : role // ignore: cast_nullable_to_non_nullable
as String,firstName: freezed == firstName ? _self.firstName : firstName // ignore: cast_nullable_to_non_nullable
as String?,lastName: freezed == lastName ? _self.lastName : lastName // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
// dart format on

View File

@@ -0,0 +1,25 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'register_request.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_RegisterRequest _$RegisterRequestFromJson(Map<String, dynamic> json) =>
_RegisterRequest(
email: json['email'] as String,
password: json['password'] as String,
role: json['role'] as String,
firstName: json['firstName'] as String?,
lastName: json['lastName'] as String?,
);
Map<String, dynamic> _$RegisterRequestToJson(_RegisterRequest instance) =>
<String, dynamic>{
'email': instance.email,
'password': instance.password,
'role': instance.role,
'firstName': instance.firstName,
'lastName': instance.lastName,
};

View File

@@ -0,0 +1,19 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_model.freezed.dart';
part 'user_model.g.dart';
@freezed
abstract class UserModel with _$UserModel {
const factory UserModel({
required String id,
required String email,
required String role,
String? firstName,
String? lastName,
String? avatar,
}) = _UserModel;
factory UserModel.fromJson(Map<String, dynamic> json) =>
_$UserModelFromJson(json);
}

View File

@@ -0,0 +1,292 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'user_model.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$UserModel {
String get id; String get email; String get role; String? get firstName; String? get lastName; String? get avatar;
/// Create a copy of UserModel
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$UserModelCopyWith<UserModel> get copyWith => _$UserModelCopyWithImpl<UserModel>(this as UserModel, _$identity);
/// Serializes this UserModel to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is UserModel&&(identical(other.id, id) || other.id == id)&&(identical(other.email, email) || other.email == email)&&(identical(other.role, role) || other.role == role)&&(identical(other.firstName, firstName) || other.firstName == firstName)&&(identical(other.lastName, lastName) || other.lastName == lastName)&&(identical(other.avatar, avatar) || other.avatar == avatar));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,email,role,firstName,lastName,avatar);
@override
String toString() {
return 'UserModel(id: $id, email: $email, role: $role, firstName: $firstName, lastName: $lastName, avatar: $avatar)';
}
}
/// @nodoc
abstract mixin class $UserModelCopyWith<$Res> {
factory $UserModelCopyWith(UserModel value, $Res Function(UserModel) _then) = _$UserModelCopyWithImpl;
@useResult
$Res call({
String id, String email, String role, String? firstName, String? lastName, String? avatar
});
}
/// @nodoc
class _$UserModelCopyWithImpl<$Res>
implements $UserModelCopyWith<$Res> {
_$UserModelCopyWithImpl(this._self, this._then);
final UserModel _self;
final $Res Function(UserModel) _then;
/// Create a copy of UserModel
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? email = null,Object? role = null,Object? firstName = freezed,Object? lastName = freezed,Object? avatar = freezed,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable
as String,role: null == role ? _self.role : role // ignore: cast_nullable_to_non_nullable
as String,firstName: freezed == firstName ? _self.firstName : firstName // ignore: cast_nullable_to_non_nullable
as String?,lastName: freezed == lastName ? _self.lastName : lastName // ignore: cast_nullable_to_non_nullable
as String?,avatar: freezed == avatar ? _self.avatar : avatar // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// Adds pattern-matching-related methods to [UserModel].
extension UserModelPatterns on UserModel {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _UserModel value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _UserModel() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _UserModel value) $default,){
final _that = this;
switch (_that) {
case _UserModel():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _UserModel value)? $default,){
final _that = this;
switch (_that) {
case _UserModel() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String email, String role, String? firstName, String? lastName, String? avatar)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _UserModel() when $default != null:
return $default(_that.id,_that.email,_that.role,_that.firstName,_that.lastName,_that.avatar);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String email, String role, String? firstName, String? lastName, String? avatar) $default,) {final _that = this;
switch (_that) {
case _UserModel():
return $default(_that.id,_that.email,_that.role,_that.firstName,_that.lastName,_that.avatar);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String email, String role, String? firstName, String? lastName, String? avatar)? $default,) {final _that = this;
switch (_that) {
case _UserModel() when $default != null:
return $default(_that.id,_that.email,_that.role,_that.firstName,_that.lastName,_that.avatar);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _UserModel implements UserModel {
const _UserModel({required this.id, required this.email, required this.role, this.firstName, this.lastName, this.avatar});
factory _UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);
@override final String id;
@override final String email;
@override final String role;
@override final String? firstName;
@override final String? lastName;
@override final String? avatar;
/// Create a copy of UserModel
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$UserModelCopyWith<_UserModel> get copyWith => __$UserModelCopyWithImpl<_UserModel>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$UserModelToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _UserModel&&(identical(other.id, id) || other.id == id)&&(identical(other.email, email) || other.email == email)&&(identical(other.role, role) || other.role == role)&&(identical(other.firstName, firstName) || other.firstName == firstName)&&(identical(other.lastName, lastName) || other.lastName == lastName)&&(identical(other.avatar, avatar) || other.avatar == avatar));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,email,role,firstName,lastName,avatar);
@override
String toString() {
return 'UserModel(id: $id, email: $email, role: $role, firstName: $firstName, lastName: $lastName, avatar: $avatar)';
}
}
/// @nodoc
abstract mixin class _$UserModelCopyWith<$Res> implements $UserModelCopyWith<$Res> {
factory _$UserModelCopyWith(_UserModel value, $Res Function(_UserModel) _then) = __$UserModelCopyWithImpl;
@override @useResult
$Res call({
String id, String email, String role, String? firstName, String? lastName, String? avatar
});
}
/// @nodoc
class __$UserModelCopyWithImpl<$Res>
implements _$UserModelCopyWith<$Res> {
__$UserModelCopyWithImpl(this._self, this._then);
final _UserModel _self;
final $Res Function(_UserModel) _then;
/// Create a copy of UserModel
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? email = null,Object? role = null,Object? firstName = freezed,Object? lastName = freezed,Object? avatar = freezed,}) {
return _then(_UserModel(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,email: null == email ? _self.email : email // ignore: cast_nullable_to_non_nullable
as String,role: null == role ? _self.role : role // ignore: cast_nullable_to_non_nullable
as String,firstName: freezed == firstName ? _self.firstName : firstName // ignore: cast_nullable_to_non_nullable
as String?,lastName: freezed == lastName ? _self.lastName : lastName // ignore: cast_nullable_to_non_nullable
as String?,avatar: freezed == avatar ? _self.avatar : avatar // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
// dart format on

View File

@@ -0,0 +1,26 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_UserModel _$UserModelFromJson(Map<String, dynamic> json) => _UserModel(
id: json['id'] as String,
email: json['email'] as String,
role: json['role'] as String,
firstName: json['firstName'] as String?,
lastName: json['lastName'] as String?,
avatar: json['avatar'] as String?,
);
Map<String, dynamic> _$UserModelToJson(_UserModel instance) =>
<String, dynamic>{
'id': instance.id,
'email': instance.email,
'role': instance.role,
'firstName': instance.firstName,
'lastName': instance.lastName,
'avatar': instance.avatar,
};

View File

@@ -0,0 +1,159 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/core/network/api_exceptions.dart';
import 'package:real_estate_mobile/features/auth/data/auth_repository.dart';
import 'package:real_estate_mobile/features/auth/data/models/register_request.dart';
import 'package:real_estate_mobile/features/auth/data/models/user_model.dart';
// Auth state
enum AuthStatus { initial, loading, success, error }
class AuthState {
final AuthStatus status;
final UserModel? user;
final String? errorMessage;
final List<FieldError> fieldErrors;
final String registeredEmail;
const AuthState({
this.status = AuthStatus.initial,
this.user,
this.errorMessage,
this.fieldErrors = const [],
this.registeredEmail = '',
});
AuthState copyWith({
AuthStatus? status,
UserModel? user,
String? errorMessage,
List<FieldError>? fieldErrors,
String? registeredEmail,
}) {
return AuthState(
status: status ?? this.status,
user: user ?? this.user,
errorMessage: errorMessage,
fieldErrors: fieldErrors ?? this.fieldErrors,
registeredEmail: registeredEmail ?? this.registeredEmail,
);
}
String? getFieldError(String fieldName) {
final match = fieldErrors.where((e) => e.field == fieldName);
if (match.isEmpty) return null;
return match.first.errors.isNotEmpty ? match.first.errors.first : null;
}
}
// Auth notifier
class AuthNotifier extends StateNotifier<AuthState> {
final AuthRepository _repository;
AuthNotifier(this._repository) : super(const AuthState());
Future<void> login({
required String email,
required String password,
}) async {
state = state.copyWith(
status: AuthStatus.loading,
errorMessage: null,
fieldErrors: [],
);
try {
final result = await _repository.login(
email: email,
password: password,
);
if (result['requiresTwoFactor'] == true) {
state = state.copyWith(
status: AuthStatus.error,
errorMessage: '2FA verification required',
);
return;
}
state = state.copyWith(
status: AuthStatus.success,
user: result['user'] as UserModel,
);
} on ApiException catch (e) {
state = state.copyWith(
status: AuthStatus.error,
errorMessage: e.fieldErrors.isNotEmpty
? 'Please fix the errors below'
: e.message,
fieldErrors: e.fieldErrors,
);
} catch (e) {
state = state.copyWith(
status: AuthStatus.error,
errorMessage: 'An unexpected error occurred',
);
}
}
Future<void> register({
required String name,
required String email,
required String password,
required String role,
}) async {
state = state.copyWith(
status: AuthStatus.loading,
errorMessage: null,
fieldErrors: [],
);
// Split name into firstName and lastName
final nameParts = name.trim().split(RegExp(r'\s+'));
final firstName = nameParts.first;
final lastName = nameParts.length > 1 ? nameParts.sublist(1).join(' ') : null;
try {
final user = await _repository.register(
RegisterRequest(
email: email,
password: password,
role: role,
firstName: firstName,
lastName: lastName,
),
);
state = state.copyWith(
status: AuthStatus.success,
user: user,
registeredEmail: email,
);
} on ApiException catch (e) {
state = state.copyWith(
status: AuthStatus.error,
errorMessage: e.fieldErrors.isNotEmpty
? 'Please fix the errors below'
: e.message,
fieldErrors: e.fieldErrors,
);
} catch (e) {
state = state.copyWith(
status: AuthStatus.error,
errorMessage: 'An unexpected error occurred',
);
}
}
void reset() {
state = const AuthState();
}
}
// Providers
final authRepositoryProvider = Provider<AuthRepository>((ref) {
return AuthRepository();
});
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
return AuthNotifier(ref.watch(authRepositoryProvider));
});

View File

@@ -0,0 +1,252 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/auth_text_field.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/or_divider.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/role_toggle.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/social_login_buttons.dart';
class LoginScreen extends ConsumerStatefulWidget {
const LoginScreen({super.key});
@override
ConsumerState<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends ConsumerState<LoginScreen> {
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
String _selectedRole = 'USER';
bool _obscurePassword = true;
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
String? _validateLocally() {
if (_emailController.text.trim().isEmpty) {
return 'Please enter your email';
}
if (_passwordController.text.isEmpty) {
return 'Please enter a password';
}
return null;
}
void _handleLogin() {
final localError = _validateLocally();
if (localError != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(localError),
behavior: SnackBarBehavior.floating,
),
);
return;
}
ref.read(authProvider.notifier).login(
email: _emailController.text.trim(),
password: _passwordController.text,
);
}
@override
Widget build(BuildContext context) {
final authState = ref.watch(authProvider);
final isLoading = authState.status == AuthStatus.loading;
return Scaffold(
body: Container(
width: double.infinity,
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [AppColors.gradientStart, AppColors.gradientEnd],
),
),
child: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
const SizedBox(height: 40),
// Logo
Image.asset(
'assets/icons/logo.png',
width: 143,
height: 41,
),
const SizedBox(height: 24),
// Title
const Text(
'Login',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 25,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
),
const SizedBox(height: 24),
// Role toggle (User / Admin)
RoleToggle(
selectedRole: _selectedRole,
onChanged: (role) => setState(() => _selectedRole = role),
),
const SizedBox(height: 20),
// Subtitle
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Login or create an account to enjoy FREE consultation on all property inquiries.',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'SourceSerif4',
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.primaryDark,
),
),
),
const SizedBox(height: 24),
// Error banner
if (authState.errorMessage != null &&
authState.fieldErrors.isEmpty) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: AppColors.errorBg,
border: Border.all(color: AppColors.errorBorder),
borderRadius: BorderRadius.circular(7),
),
child: Text(
authState.errorMessage!,
style: const TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.error,
),
),
),
const SizedBox(height: 16),
],
// Name field
AuthTextField(
hintText: 'Name',
controller: _nameController,
keyboardType: TextInputType.name,
),
const SizedBox(height: 16),
// Email field
AuthTextField(
hintText: 'Email',
controller: _emailController,
keyboardType: TextInputType.emailAddress,
errorText: authState.getFieldError('email'),
),
const SizedBox(height: 16),
// Password field
AuthTextField(
hintText: 'Password',
controller: _passwordController,
obscureText: _obscurePassword,
textInputAction: TextInputAction.done,
errorText: authState.getFieldError('password'),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility_off
: Icons.visibility,
color: AppColors.hintText,
size: 22,
),
onPressed: () =>
setState(() => _obscurePassword = !_obscurePassword),
),
),
const SizedBox(height: 24),
// Login button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: isLoading ? null : _handleLogin,
child: isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.primaryDark,
),
)
: const Text('Login'),
),
),
const SizedBox(height: 24),
// Don't have an account? Sign up
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Don't have an account? ",
style: TextStyle(
fontFamily: 'SourceSerif4',
fontSize: 14,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
),
GestureDetector(
onTap: () => context.go('/signup'),
child: const Text(
'Sign up',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.primaryDark,
),
),
),
],
),
const SizedBox(height: 24),
// Or divider
const OrDivider(),
const SizedBox(height: 24),
// Social login buttons
const SocialLoginButtons(),
const SizedBox(height: 40),
],
),
),
),
),
);
}
}

View File

@@ -0,0 +1,359 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/auth_text_field.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/or_divider.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/role_toggle.dart';
import 'package:real_estate_mobile/features/auth/presentation/widgets/social_login_buttons.dart';
import 'package:go_router/go_router.dart';
class SignupScreen extends ConsumerStatefulWidget {
const SignupScreen({super.key});
@override
ConsumerState<SignupScreen> createState() => _SignupScreenState();
}
class _SignupScreenState extends ConsumerState<SignupScreen> {
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
String _selectedRole = 'USER';
bool _obscurePassword = true;
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
String? _validateLocally() {
if (_nameController.text.trim().isEmpty) {
return 'Please enter your name';
}
if (_emailController.text.trim().isEmpty) {
return 'Please enter your email';
}
if (_passwordController.text.isEmpty) {
return 'Please enter a password';
}
return null;
}
void _handleSignup() {
final localError = _validateLocally();
if (localError != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(localError),
behavior: SnackBarBehavior.floating,
),
);
return;
}
ref.read(authProvider.notifier).register(
name: _nameController.text.trim(),
email: _emailController.text.trim(),
password: _passwordController.text,
role: _selectedRole,
);
}
@override
Widget build(BuildContext context) {
final authState = ref.watch(authProvider);
return Scaffold(
body: Container(
width: double.infinity,
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [AppColors.gradientStart, AppColors.gradientEnd],
),
),
child: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: authState.status == AuthStatus.success
? _buildSuccessContent(authState)
: _buildFormContent(authState),
),
),
),
);
}
Widget _buildSuccessContent(AuthState authState) {
return Padding(
padding: const EdgeInsets.only(top: 80),
child: Container(
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(20),
),
child: Column(
children: [
const Icon(
Icons.check_circle_outline,
size: 64,
color: AppColors.success,
),
const SizedBox(height: 24),
const Text(
'Check Your Email',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 24,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
),
const SizedBox(height: 12),
Text(
'We\'ve sent a verification link to ',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark.withValues(alpha: 0.7),
),
),
Text(
authState.registeredEmail,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.primaryDark,
),
),
const SizedBox(height: 4),
Text(
'Please check your inbox and click the link to verify your account before logging in.',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark.withValues(alpha: 0.7),
),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {
ref.read(authProvider.notifier).reset();
context.go('/login');
},
child: const Text('Go to Login'),
),
),
const SizedBox(height: 16),
Text(
'Didn\'t receive the email? Check your spam folder or contact support.',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 12,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark.withValues(alpha: 0.5),
),
),
],
),
),
);
}
Widget _buildFormContent(AuthState authState) {
final isLoading = authState.status == AuthStatus.loading;
return Column(
children: [
const SizedBox(height: 40),
// Logo
Image.asset(
'assets/icons/logo.png',
width: 143,
height: 41,
),
const SizedBox(height: 24),
// Title
const Text(
'Sign Up',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 30,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
),
const SizedBox(height: 24),
// Role toggle
RoleToggle(
selectedRole: _selectedRole,
onChanged: (role) => setState(() => _selectedRole = role),
),
const SizedBox(height: 20),
// Subtitle
Text(
'Enter Your Name to Continue',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark.withValues(alpha: 0.7),
),
),
const SizedBox(height: 20),
// Error banner
if (authState.errorMessage != null &&
authState.fieldErrors.isEmpty) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: AppColors.errorBg,
border: Border.all(color: AppColors.errorBorder),
borderRadius: BorderRadius.circular(20),
),
child: Text(
authState.errorMessage!,
style: const TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.error,
),
),
),
const SizedBox(height: 16),
],
// Name field
AuthTextField(
hintText: 'Name',
controller: _nameController,
keyboardType: TextInputType.name,
errorText: authState.getFieldError('firstName'),
),
const SizedBox(height: 16),
// Email field
AuthTextField(
hintText: 'Email',
controller: _emailController,
keyboardType: TextInputType.emailAddress,
errorText: authState.getFieldError('email'),
),
const SizedBox(height: 16),
// Password field
AuthTextField(
hintText: 'Password',
controller: _passwordController,
obscureText: _obscurePassword,
textInputAction: TextInputAction.done,
errorText: authState.getFieldError('password'),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility_off : Icons.visibility,
color: AppColors.hintText,
size: 22,
),
onPressed: () =>
setState(() => _obscurePassword = !_obscurePassword),
),
),
Padding(
padding: const EdgeInsets.only(top: 8, left: 8),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'Min 8 chars, 1 uppercase, 1 lowercase, 1 number, 1 special character',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 12,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark.withValues(alpha: 0.6),
),
),
),
),
const SizedBox(height: 24),
// Sign Up button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: isLoading ? null : _handleSignup,
child: isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.primaryDark,
),
)
: const Text('Sign Up'),
),
),
const SizedBox(height: 24),
// Already have account
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Already Have An Account ? ',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark,
),
),
GestureDetector(
onTap: () => context.go('/login'),
child: const Text(
'Login',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w400,
color: AppColors.primaryDark,
),
),
),
],
),
const SizedBox(height: 24),
// Or divider
const OrDivider(),
const SizedBox(height: 24),
// Social login buttons
const SocialLoginButtons(),
const SizedBox(height: 40),
],
);
}
}

View File

@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
class AuthTextField extends StatelessWidget {
final String hintText;
final TextEditingController controller;
final bool obscureText;
final TextInputType keyboardType;
final Widget? suffixIcon;
final String? errorText;
final TextInputAction textInputAction;
const AuthTextField({
super.key,
required this.hintText,
required this.controller,
this.obscureText = false,
this.keyboardType = TextInputType.text,
this.suffixIcon,
this.errorText,
this.textInputAction = TextInputAction.next,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: controller,
obscureText: obscureText,
keyboardType: keyboardType,
textInputAction: textInputAction,
style: const TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark,
),
decoration: InputDecoration(
hintText: hintText,
suffixIcon: suffixIcon,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: errorText != null
? const BorderSide(color: AppColors.error, width: 1.5)
: BorderSide.none,
),
),
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 4, left: 8),
child: Text(
errorText!,
style: const TextStyle(
fontFamily: 'Fractul',
fontSize: 12,
fontWeight: FontWeight.w300,
color: AppColors.error,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,32 @@
import 'package:flutter/material.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
class OrDivider extends StatelessWidget {
const OrDivider({super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
const Expanded(
child: Divider(color: AppColors.divider, thickness: 1),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Or',
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: AppColors.primaryDark.withValues(alpha: 0.6),
),
),
),
const Expanded(
child: Divider(color: AppColors.divider, thickness: 1),
),
],
);
}
}

View File

@@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
class RoleToggle extends StatelessWidget {
final String selectedRole;
final ValueChanged<String> onChanged;
const RoleToggle({
super.key,
required this.selectedRole,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: AppColors.inputFill,
borderRadius: BorderRadius.circular(20),
),
padding: const EdgeInsets.all(2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_buildToggleButton('User', 'USER'),
_buildToggleButton('Admin', 'AGENT'),
],
),
);
}
Widget _buildToggleButton(String label, String role) {
final isSelected = selectedRole == role;
return GestureDetector(
onTap: () => onChanged(role),
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 10),
decoration: BoxDecoration(
color: isSelected ? AppColors.primaryDark : Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: Text(
label,
style: TextStyle(
fontFamily: 'Fractul',
fontSize: 14,
fontWeight: FontWeight.w300,
color: isSelected ? AppColors.inputFill : AppColors.primaryDark,
),
),
),
);
}
}

View File

@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
class SocialLoginButtons extends StatelessWidget {
const SocialLoginButtons({super.key});
void _showComingSoon(BuildContext context) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Coming soon'),
duration: Duration(seconds: 1),
behavior: SnackBarBehavior.floating,
),
);
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Apple
_SocialButton(
onTap: () => _showComingSoon(context),
child: const Icon(
Icons.apple,
size: 28,
color: AppColors.primaryDark,
),
),
const SizedBox(width: 32),
// Google
_SocialButton(
onTap: () => _showComingSoon(context),
child: SvgPicture.asset(
'assets/icons/google.svg',
width: 24,
height: 24,
),
),
const SizedBox(width: 32),
// X (Twitter)
_SocialButton(
onTap: () => _showComingSoon(context),
child: SvgPicture.asset(
'assets/icons/x.svg',
width: 24,
height: 24,
),
),
const SizedBox(width: 32),
// Facebook
_SocialButton(
onTap: () => _showComingSoon(context),
child: SvgPicture.asset(
'assets/icons/facebook.svg',
width: 24,
height: 24,
),
),
],
);
}
}
class _SocialButton extends StatelessWidget {
final VoidCallback onTap;
final Widget child;
const _SocialButton({
required this.onTap,
required this.child,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: SizedBox(
width: 40,
height: 40,
child: Center(child: child),
),
);
}
}

View File

@@ -1,122 +1,25 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/config/app_config.dart';
import 'package:real_estate_mobile/core/theme/app_theme.dart';
import 'package:real_estate_mobile/routing/app_router.dart';
void main() {
runApp(const MyApp());
Future<void> mainCommon(Flavor flavor) async {
WidgetsFlutterBinding.ensureInitialized();
await AppConfig.init(flavor);
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: .center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
return MaterialApp.router(
title: 'RE-QuestN',
theme: AppTheme.light,
routerConfig: AppRouter.router,
debugShowCheckedModeBanner: false,
);
}
}

4
lib/main_demo.dart Normal file
View File

@@ -0,0 +1,4 @@
import 'package:real_estate_mobile/config/app_config.dart';
import 'package:real_estate_mobile/main.dart';
void main() => mainCommon(Flavor.demo);

4
lib/main_dev.dart Normal file
View File

@@ -0,0 +1,4 @@
import 'package:real_estate_mobile/config/app_config.dart';
import 'package:real_estate_mobile/main.dart';
void main() => mainCommon(Flavor.dev);

4
lib/main_local.dart Normal file
View File

@@ -0,0 +1,4 @@
import 'package:real_estate_mobile/config/app_config.dart';
import 'package:real_estate_mobile/main.dart';
void main() => mainCommon(Flavor.local);

View File

@@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:real_estate_mobile/features/auth/presentation/screens/login_screen.dart';
import 'package:real_estate_mobile/features/auth/presentation/screens/signup_screen.dart';
class AppRouter {
AppRouter._();
static final GoRouter router = GoRouter(
initialLocation: '/signup',
routes: [
GoRoute(
path: '/signup',
builder: (context, state) => const SignupScreen(),
),
GoRoute(
path: '/login',
builder: (context, state) => const LoginScreen(),
),
],
);
}