feat: refactor code

This commit is contained in:
2026-06-17 12:57:28 +03:30
parent e9f294fa19
commit 519752b478
106 changed files with 3459 additions and 2309 deletions
@@ -0,0 +1,16 @@
import '../../../../../core/storage/token_storage.dart';
/// ذخیره‌ی محلیِ توکن احراز هویت.
class AuthLocalData {
final TokenStorage _storage;
AuthLocalData(this._storage);
Future<void> saveToken(String token) => _storage.write(token);
Future<String?> readToken() => _storage.read();
Future<void> clearToken() => _storage.clear();
Future<bool> hasToken() async {
final t = await _storage.read();
return t != null && t.isNotEmpty;
}
}
@@ -0,0 +1,20 @@
import 'package:dio/dio.dart';
import '../../../../../core/locator/locator.dart';
import '../../../../../core/network/api_provider_imp.dart';
/// تماس‌های خامِ HTTP مربوط به احراز هویت (خروجی Response).
class AuthApiProvider {
ApiProviderImp get _api => locator<ApiProviderImp>();
Future<Response> loginOtp(String mobile) =>
_api.post('/auth/login-otp', body: {'mobile': mobile});
Future<Response> checkOtp(String mobile, String token) =>
_api.post('/auth/check-otp', body: {'mobile': mobile, 'token': token});
Future<Response> updateProfile(String firstName, String avatar) =>
_api.post('/profile', body: {'first_name': firstName, 'avatar': avatar});
Future<Response> me() => _api.get('/me');
}
@@ -0,0 +1,18 @@
import '../../domain/entities/user_entity.dart';
/// مدلِ داده‌ی کاربر؛ از JSON ساخته شده و به UserEntity نگاشت می‌شود.
class UserModel extends UserEntity {
const UserModel({
required super.id,
required super.mobile,
super.firstName,
super.avatar,
});
factory UserModel.fromJson(Map<String, dynamic> j) => UserModel(
id: (j['id'] ?? 0) as int,
mobile: (j['mobile'] ?? '') as String,
firstName: j['first_name'] as String?,
avatar: j['avatar'] as String?,
);
}
@@ -0,0 +1,65 @@
import 'package:dio/dio.dart';
import '../../../../core/error/custom_error.dart';
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../../domain/entities/user_entity.dart';
import '../../domain/repository/auth_repository.dart';
import '../data_source/local/auth_local_data.dart';
import '../data_source/remote/auth_api_provider.dart';
import '../model/user_model.dart';
class AuthRepositoryImpl extends AuthRepository {
final AuthApiProvider api;
final AuthLocalData local;
AuthRepositoryImpl(this.api, this.local);
@override
Future<DataState<String>> loginOtp(String mobile) async {
final Response res = await api.loginOtp(mobile);
if (res.statusCode == 200) {
return const DataSuccess('ok');
}
return DataError(errorConvertor(res.statusCode, _msg(res)));
}
@override
Future<DataState<UserEntity>> checkOtp(OtpParams params) async {
final Response res = await api.checkOtp(params.mobile, params.token);
if (res.statusCode == 200) {
final token = res.data['token'] as String?;
if (token == null || token.isEmpty) {
return const DataError('پاسخ نامعتبر از سرور');
}
await local.saveToken(token);
return DataSuccess(UserModel.fromJson(
Map<String, dynamic>.from(res.data['user'] as Map)));
}
return DataError(errorConvertor(res.statusCode, _msg(res)));
}
@override
Future<DataState<UserEntity>> updateProfile(ProfileParams params) async {
final Response res = await api.updateProfile(params.firstName, params.avatar);
if (res.statusCode == 200) {
return DataSuccess(UserModel.fromJson(
Map<String, dynamic>.from(res.data['user'] as Map)));
}
return DataError(errorConvertor(res.statusCode, _msg(res)));
}
@override
Future<DataState<String>> logout() async {
await local.clearToken();
return const DataSuccess('ok');
}
@override
Future<bool> isLoggedIn() => local.hasToken();
String? _msg(Response res) {
final d = res.data;
if (d is Map && d['message'] != null) return d['message'].toString();
return null;
}
}
@@ -0,0 +1,16 @@
/// موجودیتِ کاربر (نام نمایشی و آواتار برای استفاده در UI).
class UserEntity {
final int id;
final String mobile;
final String? firstName;
final String? avatar;
const UserEntity({
required this.id,
required this.mobile,
this.firstName,
this.avatar,
});
bool get hasName => firstName != null && firstName!.trim().isNotEmpty;
}
@@ -0,0 +1,17 @@
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../entities/user_entity.dart';
/// قرارداد لایه‌ی داده‌ی احراز هویت (پیاده‌سازی در data/repository).
abstract class AuthRepository {
Future<DataState<String>> loginOtp(String mobile);
/// بررسی کد؛ توکن را ذخیره کرده و کاربرِ احرازشده را برمی‌گرداند.
Future<DataState<UserEntity>> checkOtp(OtpParams params);
Future<DataState<UserEntity>> updateProfile(ProfileParams params);
Future<DataState<String>> logout();
Future<bool> isLoggedIn();
}
@@ -0,0 +1,13 @@
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../entities/user_entity.dart';
import '../repository/auth_repository.dart';
class CheckOtpUseCase implements UseCase<DataState<UserEntity>, OtpParams> {
final AuthRepository repository;
CheckOtpUseCase(this.repository);
@override
Future<DataState<UserEntity>> call(OtpParams params) =>
repository.checkOtp(params);
}
@@ -0,0 +1,11 @@
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../repository/auth_repository.dart';
class LoginUseCase implements UseCase<DataState<String>, String> {
final AuthRepository repository;
LoginUseCase(this.repository);
@override
Future<DataState<String>> call(String params) => repository.loginOtp(params);
}
@@ -0,0 +1,11 @@
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../repository/auth_repository.dart';
class LogoutUseCase implements UseCase<DataState<String>, NoParams> {
final AuthRepository repository;
LogoutUseCase(this.repository);
@override
Future<DataState<String>> call(NoParams params) => repository.logout();
}
@@ -0,0 +1,14 @@
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../entities/user_entity.dart';
import '../repository/auth_repository.dart';
class UpdateProfileUseCase
implements UseCase<DataState<UserEntity>, ProfileParams> {
final AuthRepository repository;
UpdateProfileUseCase(this.repository);
@override
Future<DataState<UserEntity>> call(ProfileParams params) =>
repository.updateProfile(params);
}
@@ -0,0 +1,63 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../../domain/use_cases/check_otp_usecase.dart';
import '../../domain/use_cases/login_usecase.dart';
import '../../domain/use_cases/logout_usecase.dart';
import '../../domain/use_cases/update_profile_usecase.dart';
import 'auth_event.dart';
import 'auth_state.dart';
import 'login_status.dart';
import 'otp_status.dart';
import 'profile_status.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final LoginUseCase loginUseCase;
final CheckOtpUseCase checkOtpUseCase;
final UpdateProfileUseCase updateProfileUseCase;
final LogoutUseCase logoutUseCase;
AuthBloc(
this.loginUseCase,
this.checkOtpUseCase,
this.updateProfileUseCase,
this.logoutUseCase,
) : super(AuthState.initial()) {
on<LoginOtpEvent>((event, emit) async {
emit(state.copyWith(mobile: event.mobile, loginStatus: LoginLoading()));
final res = await loginUseCase(event.mobile);
if (res is DataSuccess) {
emit(state.copyWith(loginStatus: LoginSuccess()));
} else {
emit(state.copyWith(loginStatus: LoginError(res.error!)));
}
});
on<CheckOtpEvent>((event, emit) async {
emit(state.copyWith(otpStatus: OtpLoading()));
final res = await checkOtpUseCase(OtpParams(state.mobile, event.token));
if (res is DataSuccess) {
emit(state.copyWith(otpStatus: OtpSuccess(res.data!.hasName)));
} else {
emit(state.copyWith(otpStatus: OtpError(res.error!)));
}
});
on<UpdateProfileEvent>((event, emit) async {
emit(state.copyWith(profileStatus: ProfileLoading()));
final res = await updateProfileUseCase(
ProfileParams(event.firstName, event.avatar));
if (res is DataSuccess) {
emit(state.copyWith(profileStatus: ProfileSuccess()));
} else {
emit(state.copyWith(profileStatus: ProfileError(res.error!)));
}
});
on<LogoutEvent>((event, emit) async {
await logoutUseCase(const NoParams());
emit(AuthState.initial());
});
}
}
@@ -0,0 +1,19 @@
abstract class AuthEvent {}
class LoginOtpEvent extends AuthEvent {
final String mobile;
LoginOtpEvent(this.mobile);
}
class CheckOtpEvent extends AuthEvent {
final String token;
CheckOtpEvent(this.token);
}
class UpdateProfileEvent extends AuthEvent {
final String firstName;
final String avatar;
UpdateProfileEvent(this.firstName, this.avatar);
}
class LogoutEvent extends AuthEvent {}
@@ -0,0 +1,37 @@
import 'login_status.dart';
import 'otp_status.dart';
import 'profile_status.dart';
class AuthState {
final String mobile; // شماره‌ی در حال احراز (برای صفحه‌ی کد)
final LoginStatus loginStatus;
final OtpStatus otpStatus;
final ProfileStatus profileStatus;
AuthState({
required this.mobile,
required this.loginStatus,
required this.otpStatus,
required this.profileStatus,
});
factory AuthState.initial() => AuthState(
mobile: '',
loginStatus: LoginInitial(),
otpStatus: OtpInitial(),
profileStatus: ProfileInitial(),
);
AuthState copyWith({
String? mobile,
LoginStatus? loginStatus,
OtpStatus? otpStatus,
ProfileStatus? profileStatus,
}) =>
AuthState(
mobile: mobile ?? this.mobile,
loginStatus: loginStatus ?? this.loginStatus,
otpStatus: otpStatus ?? this.otpStatus,
profileStatus: profileStatus ?? this.profileStatus,
);
}
@@ -0,0 +1,12 @@
abstract class LoginStatus {}
class LoginInitial extends LoginStatus {}
class LoginLoading extends LoginStatus {}
class LoginSuccess extends LoginStatus {}
class LoginError extends LoginStatus {
final String message;
LoginError(this.message);
}
@@ -0,0 +1,15 @@
abstract class OtpStatus {}
class OtpInitial extends OtpStatus {}
class OtpLoading extends OtpStatus {}
class OtpSuccess extends OtpStatus {
final bool hasName; // اگر نام نداشته باشد، باید به صفحه‌ی انتخاب نام برود
OtpSuccess(this.hasName);
}
class OtpError extends OtpStatus {
final String message;
OtpError(this.message);
}
@@ -0,0 +1,12 @@
abstract class ProfileStatus {}
class ProfileInitial extends ProfileStatus {}
class ProfileLoading extends ProfileStatus {}
class ProfileSuccess extends ProfileStatus {}
class ProfileError extends ProfileStatus {
final String message;
ProfileError(this.message);
}
@@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/widgets/game_ui.dart';
import '../bloc/auth_bloc.dart';
import '../bloc/auth_event.dart';
import '../bloc/auth_state.dart';
import '../bloc/login_status.dart';
/// صفحه‌ی ورود شماره موبایل.
class MobileScreen extends StatefulWidget {
const MobileScreen({super.key});
@override
State<MobileScreen> createState() => _MobileScreenState();
}
class _MobileScreenState extends State<MobileScreen> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
bool get _valid => RegExp(r'^09\d{9}$').hasMatch(_controller.text.trim());
@override
Widget build(BuildContext context) {
return Scaffold(
body: GameBackground(
child: BlocConsumer<AuthBloc, AuthState>(
listenWhen: (a, b) => a.loginStatus != b.loginStatus,
listener: (context, state) {
final s = state.loginStatus;
if (s is LoginSuccess) {
context.push('/otp');
} else if (s is LoginError) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(s.message)));
}
},
builder: (context, state) {
final loading = state.loginStatus is LoginLoading;
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const GlowText('سلطان حکم', size: 40),
const SizedBox(height: 28),
GamePanel(
padding: const EdgeInsets.all(22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('برای ورود شماره موبایلت رو وارد کن',
style: TextStyle(color: Colors.white70)),
const SizedBox(height: 20),
TextField(
controller: _controller,
keyboardType: TextInputType.phone,
textAlign: TextAlign.center,
style:
const TextStyle(fontSize: 20, letterSpacing: 2),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(11),
],
decoration:
const InputDecoration(hintText: '09xxxxxxxxx'),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 20),
GameButton(
label: 'دریافت کد',
width: double.infinity,
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
onTap: (!_valid || loading)
? null
: () => context
.read<AuthBloc>()
.add(LoginOtpEvent(_controller.text.trim())),
),
],
),
),
],
),
),
);
},
),
),
);
}
}
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../bloc/auth_bloc.dart';
import '../bloc/auth_event.dart';
import '../bloc/auth_state.dart';
import '../bloc/otp_status.dart';
/// صفحه‌ی ورود کد یک‌بارمصرف (۵ رقمی).
class OtpScreen extends StatefulWidget {
const OtpScreen({super.key});
@override
State<OtpScreen> createState() => _OtpScreenState();
}
class _OtpScreenState extends State<OtpScreen> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
bool get _valid => _controller.text.trim().length == 5;
@override
Widget build(BuildContext context) {
return Scaffold(
body: GameBackground(
child: BlocConsumer<AuthBloc, AuthState>(
listenWhen: (a, b) => a.otpStatus != b.otpStatus,
listener: (context, state) {
final s = state.otpStatus;
if (s is OtpSuccess) {
context.go(s.hasName ? '/lobby' : '/setup');
} else if (s is OtpError) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(s.message)));
}
},
builder: (context, state) {
final loading = state.otpStatus is OtpLoading;
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const GlowText('تأیید کد', size: 32),
const SizedBox(height: 24),
GamePanel(
padding: const EdgeInsets.all(22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('کد پیامک‌شده به ${state.mobile} را وارد کنید',
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70)),
const SizedBox(height: 20),
TextField(
controller: _controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 28, letterSpacing: 12),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(5),
],
decoration:
const InputDecoration(hintText: '- - - - -'),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 20),
GameButton(
label: 'ورود',
width: double.infinity,
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
onTap: (!_valid || loading)
? null
: () => context
.read<AuthBloc>()
.add(CheckOtpEvent(_controller.text.trim())),
),
TextButton(
onPressed: loading ? null : () => context.pop(),
child: const Text('تغییر شماره',
style: TextStyle(color: AppColors.gold)),
),
],
),
),
],
),
),
);
},
),
),
);
}
}
@@ -0,0 +1,146 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:random_avatar/random_avatar.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../bloc/auth_bloc.dart';
import '../bloc/auth_event.dart';
import '../bloc/auth_state.dart';
import '../bloc/profile_status.dart';
/// صفحه‌ی انتخاب نام و آواتار پس از اولین ورود.
class ProfileSetupScreen extends StatefulWidget {
const ProfileSetupScreen({super.key});
@override
State<ProfileSetupScreen> createState() => _ProfileSetupScreenState();
}
class _ProfileSetupScreenState extends State<ProfileSetupScreen> {
final _name = TextEditingController();
late List<String> _seeds;
int _selected = 0;
@override
void initState() {
super.initState();
_seeds = List.generate(12, (i) => 'hakem-${i + 1}');
}
@override
void dispose() {
_name.dispose();
super.dispose();
}
bool get _valid => _name.text.trim().length >= 2;
@override
Widget build(BuildContext context) {
return Scaffold(
body: GameBackground(
child: BlocConsumer<AuthBloc, AuthState>(
listenWhen: (a, b) => a.profileStatus != b.profileStatus,
listener: (context, state) {
final s = state.profileStatus;
if (s is ProfileSuccess) {
context.go('/lobby');
} else if (s is ProfileError) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(s.message)));
}
},
builder: (context, state) {
final saving = state.profileStatus is ProfileLoading;
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const GlowText('انتخاب نام و آواتار', size: 26),
const SizedBox(height: 20),
GamePanel(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
shape: BoxShape.circle,
border:
Border.all(color: AppColors.gold, width: 2),
),
child: RandomAvatar(_seeds[_selected],
height: 84, width: 84),
),
const SizedBox(height: 14),
TextField(
controller: _name,
textAlign: TextAlign.center,
maxLength: 20,
inputFormatters: [
LengthLimitingTextInputFormatter(20),
],
decoration: const InputDecoration(
hintText: 'نام نمایشی (۲ تا ۲۰ حرف)',
counterText: ''),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 14),
const Text('یک آواتار انتخاب کن',
style: TextStyle(color: AppColors.gold)),
const SizedBox(height: 10),
GridView.count(
crossAxisCount: 4,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: [
for (var i = 0; i < _seeds.length; i++)
GestureDetector(
onTap: () => setState(() => _selected = i),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: AppColors.bgDark,
border: Border.all(
color: _selected == i
? AppColors.gold
: Colors.transparent,
width: 2.5,
),
),
child: RandomAvatar(_seeds[i]),
),
),
],
),
const SizedBox(height: 18),
GameButton(
label: saving ? 'در حال ذخیره…' : 'تأیید و ورود',
width: double.infinity,
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
onTap: (!_valid || saving)
? null
: () => context.read<AuthBloc>().add(
UpdateProfileEvent(
_name.text.trim(), _seeds[_selected])),
),
],
),
),
],
),
),
);
},
),
),
);
}
}