验证码:view
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'index.dart';
class SendcodePage extends GetView<SendcodeController> {
// 接收注册页面,传进来的手机号控制器,和发送验证码的类型
final TextEditingController? mobileController;
final String? type;
const SendcodePage({super.key,this.mobileController,this.type});
@override
Widget build(BuildContext context) {
print('父组件传进来的值${mobileController!.text},${type}');
return GetBuilder<SendcodeController>(
// 把值传递给SendcodeController控制器
init: SendcodeController(mobileController:mobileController,type:type),
id: "sendcode",
builder: (_) {
return GestureDetector(
onTap: controller.onSendCode,
child: controller.isSend ? Text(controller.title,style: TextStyle(fontSize: 14,color: Colors.grey),) : Text(controller.title,style: TextStyle(fontSize: 14,color: Color(0xfff0052d9)),),
);
},
);
}
}
验证码:controller
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_aidishi/models/request/user_send_code.dart';
import 'package:flutter_aidishi/utils/loading.dart';
import 'package:get/get.dart';
import '../../api/user.dart';
class SendcodeController extends GetxController {
// 注册页手机号控制器,获取到手机号
final TextEditingController? mobileController;
// 发送验证码的类型
final String? type;
SendcodeController({this.mobileController,this.type});
String title = '发送验证码';
bool isSend = false;
Timer? timer;
int downTime = 0;
void onSendCode() async{
Loading.show();
if(isSend) return;
var isOk = await UserApi.sendCode(UserSendCodeModel(
phone: mobileController!.text,
type: type
));
if(!isOk) return;
title = '${60}秒后重新发送';
isSend = true;
downTime = 60;
Loading.success();
// 启动倒计时
timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
if (downTime > 0) {
downTime--;
title = '${downTime}秒后重新发送';
update(["sendcode"]);
} else {
timer.cancel();
title = '发送验证码';
isSend = false;
downTime = 0;
update(["sendcode"]);
}
});
}
_initData() {
update(["sendcode"]);
}
@override
void onInit() {
super.onInit();
}
@override
void onReady() {
super.onReady();
_initData();
}
@override
void onClose() {
super.onClose();
}
}
注册页
Container(
child: TDInput(
leftLabel: '验证码',
backgroundColor: Color(0xffF5F5F5),
hintText: '请输入验证码',
controller: controller.codeController,
onChanged:(value){
controller.checkLoginButtonState();
},
needClear:false,
rightBtn: Container(
// 在这里把手机号控制器,验证码的类型,传递过去。
child: SendcodePage(mobileController:controller.mobileController,type:'register'),
),
),
),