init
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import 'shop_models.dart';
|
||||
import 'shop_repository.dart';
|
||||
|
||||
enum ShopStatus { initial, loading, loaded, error }
|
||||
|
||||
class ShopState extends Equatable {
|
||||
final ShopStatus status;
|
||||
final ShopData? data;
|
||||
final bool busy; // در حال انجام یک عملیات (خرید/انتخاب)
|
||||
|
||||
const ShopState({this.status = ShopStatus.initial, this.data, this.busy = false});
|
||||
|
||||
ShopState copyWith({ShopStatus? status, ShopData? data, bool? busy}) => ShopState(
|
||||
status: status ?? this.status,
|
||||
data: data ?? this.data,
|
||||
busy: busy ?? this.busy,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, data, busy];
|
||||
}
|
||||
|
||||
class ShopCubit extends Cubit<ShopState> {
|
||||
final ShopRepository _repo;
|
||||
ShopCubit(this._repo) : super(const ShopState());
|
||||
|
||||
Future<void> load() async {
|
||||
emit(state.copyWith(status: ShopStatus.loading));
|
||||
try {
|
||||
emit(state.copyWith(status: ShopStatus.loaded, data: await _repo.getShop()));
|
||||
} catch (_) {
|
||||
emit(state.copyWith(status: ShopStatus.error));
|
||||
}
|
||||
}
|
||||
|
||||
/// یک عملیات را اجرا، فروشگاه را بازخوانی و پیام نتیجه را برمیگرداند.
|
||||
Future<String> _run(Future<void> Function() action, String okMsg) async {
|
||||
if (state.busy) return '';
|
||||
emit(state.copyWith(busy: true));
|
||||
try {
|
||||
await action();
|
||||
final data = await _repo.getShop();
|
||||
emit(state.copyWith(status: ShopStatus.loaded, data: data, busy: false));
|
||||
return okMsg;
|
||||
} on DioException catch (e) {
|
||||
emit(state.copyWith(busy: false));
|
||||
final d = e.response?.data;
|
||||
if (d is Map && d['message'] != null) return d['message'].toString();
|
||||
return 'خطا در ارتباط با سرور';
|
||||
} catch (_) {
|
||||
emit(state.copyWith(busy: false));
|
||||
return 'خطای نامشخص';
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> buyCard(String id) => _run(() => _repo.buyCard(id), 'کارت خریداری شد');
|
||||
|
||||
Future<String> selectCard(String id) =>
|
||||
_run(() => _repo.selectCard(id), 'کارت انتخاب شد');
|
||||
|
||||
Future<String> purchase(String kind, String id) => _run(
|
||||
() => _repo.purchase(
|
||||
store: 'bazaar',
|
||||
kind: kind,
|
||||
productId: id,
|
||||
token: 'dev-$kind-$id-${DateTime.now().millisecondsSinceEpoch}',
|
||||
),
|
||||
'خرید با موفقیت انجام شد',
|
||||
);
|
||||
|
||||
Future<String> claimAd() => _run(
|
||||
() => _repo.adReward('dev-ad-${DateTime.now().millisecondsSinceEpoch}'),
|
||||
'سکه رایگان دریافت شد',
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user