login_phone_cubit.dart 2.59 KB
import 'dart:async';

import 'package:appframe/config/routes.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class LoginPhoneState extends Equatable {
  final bool agreed;
  final bool showAgreed;
  final String phone;
  final String password;
  final bool allowSend;
  final int seconds;

  const LoginPhoneState(
      {this.agreed = false,
      this.showAgreed = false,
      this.phone = '',
      this.password = '',
      this.allowSend = true,
      this.seconds = 0});

  LoginPhoneState copyWith({
    bool? agreed,
    bool? showAgreed,
    String? phone,
    String? password,
    bool? allowSend,
    int? seconds,
  }) {
    return LoginPhoneState(
      agreed: agreed ?? this.agreed,
      showAgreed: showAgreed ?? this.showAgreed,
      phone: phone ?? this.phone,
      password: password ?? this.password,
      allowSend: allowSend ?? this.allowSend,
      seconds: seconds ?? this.seconds,
    );
  }

  @override
  List<Object?> get props => [phone, password, agreed, showAgreed, allowSend, seconds];
}

class LoginPhoneCubit extends Cubit<LoginPhoneState> {
  late TextEditingController _phoneController;
  late TextEditingController _codeController;
  Timer? _timer;
  int countdown = 60; // 倒计时秒数

  TextEditingController get phoneController => _phoneController;

  TextEditingController get codeController => _codeController;

  LoginPhoneCubit(super.initialState) {
    _phoneController = TextEditingController();
    _codeController = TextEditingController();

    _phoneController.text = state.phone;
    _codeController.text = state.password;
  }

  /// 开始倒计时
  void startCountdown() {
    countdown = 60;
    emit(state.copyWith(allowSend: false, seconds: countdown));

    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      countdown--;
      if (countdown <= 0) {
        _timer?.cancel();
        emit(state.copyWith(allowSend: true, seconds: 60));
      } else {
        emit(state.copyWith(seconds: countdown));
      }
    });
  }

  /// 发送验证码
  void sendVerificationCode() {
    if (state.allowSend) {
      // 实际发送验证码的逻辑
      startCountdown(); // 开始倒计时
    }
  }

  void toggleAgreed(bool value) {
    emit(state.copyWith(agreed: value));
  }

  void goLoginMain() {
    router.go('/loginMain');
  }

  @override
  Future<void> close() async {
    try {
      _phoneController.dispose();
    } catch (e) {
      print(e);
    }

    try {
      _codeController.dispose();
    } catch (e) {
      print(e);
    }

    await super.close();
  }
}