account_cubit.dart 2.14 KB
import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
import 'package:appframe/data/repositories/phone_auth_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AccountState extends Equatable {
  final bool loaded;
  final String name;
  final String phone;
  final String nickname;
  final String imgIcon;

  const AccountState({
    this.loaded = false,
    this.name = '',
    this.phone = '',
    this.nickname = '',
    this.imgIcon = '',
  });

  AccountState copyWith({
    bool? loaded,
    String? name,
    String? phone,
    String? nickname,
    String? imgIcon,
  }) {
    return AccountState(
      loaded: loaded ?? this.loaded,
      name: name ?? this.name,
      phone: phone ?? this.phone,
      nickname: nickname ?? this.nickname,
      imgIcon: imgIcon ?? this.imgIcon,
    );
  }

  @override
  List<Object?> get props => [
        loaded,
        name,
        phone,
        nickname,
        imgIcon,
      ];
}

class AccountCubit extends Cubit<AccountState> {
  late final PhoneAuthRepository _phoneAuthRepository;

  AccountCubit(super.initialState) {
    _phoneAuthRepository = getIt.get<PhoneAuthRepository>();
    init();
  }

  Future<void> init() async {
    var sharedPreferences = getIt.get<SharedPreferences>();
    var userCode = sharedPreferences.getString('auth_userCode') ?? '';
    try {
      var result = await _phoneAuthRepository.bindCheck(userCode);
      var code = result['code'];
      var data = result['data'];
      if (code != 0) {
        return;
      }

      emit(
        state.copyWith(
          loaded: true,
          name: data['name'],
          phone: data['phone'],
          nickname: data['nickname'],
          imgIcon: data['imgIcon'],
        ),
      );
    } catch (e) {
      print(e);
    }
  }

  Future<void> goBind() async {
    String? result = await router.push(
      '/account/phone',
      extra: {
        'phone': state.phone,
      },
    );
    if (result != null && result.isNotEmpty) {
      emit(state.copyWith(phone: result));
    }
  }
}