time_widget.dart 2.53 KB
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wow_english/common/blocs/timerbloc/timer_bloc.dart';
import 'package:wow_english/common/extension/string_extension.dart';
import 'package:wow_english/common/widgets/timer_ticker.dart';

class TimerWidget extends StatelessWidget {
  const TimerWidget({super.key, required this.canSendSms});

  final bool canSendSms;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => TimerBloc(ticker: const TimerTicker()),
      child: TimerWidgetView(canSendSms: canSendSms,),
    );
  }
}

class TimerWidgetView extends StatelessWidget {

  final bool canSendSms;

  const TimerWidgetView({super.key, required this.canSendSms});


  @override
  Widget build(BuildContext context) {
    bool sendSmsIng = false;
    return BlocListener<TimerBloc,TimerState>(
      listener: (context, s) {
        if (s is RunningState) {
          sendSmsIng = true;
        } if (s is FinishedState) {
          sendSmsIng = false;
          context.read<TimerBloc>().add(ResetEvent());
        } else {
          sendSmsIng = false;
        }
      },
      child: _buildCountdownWidget(sendSmsIng:sendSmsIng),
    );
  }

  Widget _buildCountdownWidget({required bool sendSmsIng}) => BlocBuilder<TimerBloc,TimerState>(
    buildWhen: (prev, state) => prev.runtimeType != state.runtimeType,
    builder: (context,state) {
      final bloc = BlocProvider.of<TimerBloc>(context);
      final duration = bloc.state.duration;
      final secondsStr = (duration % 60).floor().toString().padLeft(2, '0');
      return GestureDetector(
        onTap: () {
          if (canSendSms && !sendSmsIng) {
            bloc.add(ResetEvent());
          }
        },
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(
                    canSendSms?'securitycode'.assetPng:'securitycode_dis'.assetPng
                ),
                fit: BoxFit.fill
            ),
          ),
          padding: const EdgeInsets.symmetric(horizontal:12.0,vertical: 15.0),
          child:  Row(
            children: [
              if (state is TimerInitial)...[
                const Text('获取验证码')
              ],
              if (state is RunningState)...[
                Text('${secondsStr}s倒计时')
              ],
              if (state is FinishedState) ...[
                const Text('获取验证码')
              ]
            ],
          ),
        ),
      );
    },
  );
}