UI效果图
实现思路
1、使用Stack层叠布局
2、创建 4 个 Container 作为显示 4个验证码的 视图
3、创建TextField覆盖在 Container 上面 设置字体位透明颜色
4、监听TextField 输入 填充 4 个 Container 刷新UI
具体代码如下
import 'package:flutter/material.dart';
import 'package:z_chat_flutter/tools/CustomStyle.dart';
import 'package:z_chat_flutter/tools/ImageConfig.dart';
import '../tools/ColorConfig.dart';
class CodeAutoFillWidget extends StatefulWidget {
const CodeAutoFillWidget({Key? key}) : super(key: key);
@override
State createState() => _CodeAutoFillWidget();
}
class _CodeAutoFillWidget extends State {
TextEditingController? control;
//定义4个长度的验证码
int maxWord = 4;
@override
void initState() {
super.initState();
control = TextEditingController();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
var codeText = "${control?.value.text}";
return Container(
height: 50,
width: 304,
child: Stack(
children: [
Row(
children: [
Container(
alignment: AlignmentDirectional.center,
width: 50,
height: 50,
margin: EdgeInsets.only(left: 15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Color0FE9EA)),
child: Text(
codeText.length > 0 ? codeText.substring(0, 1) : "",
style: CText(
s: 24.0,
),
),
),
Container(
alignment: AlignmentDirectional.center,
width: 50,
height: 50,
margin: EdgeInsets.only(left: 25),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Color0FE9EA)),
child: Text(
codeText.length > 1 ? codeText.substring(1, 2) : "",
style: CText(
s: 24.0,
),
),
),
Container(
alignment: AlignmentDirectional.center,
width: 50,
height: 50,
margin: EdgeInsets.only(left: 25),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Color0FE9EA)),
child: Text(
codeText.length > 2 ? codeText.substring(2, 3) : "",
style: CText(
s: 24.0,
),
),
),
Container(
alignment: AlignmentDirectional.center,
width: 50,
height: 50,
margin: EdgeInsets.only(left: 25),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Color0FE9EA)),
child: Text(
codeText.length > 3 ? codeText.substring(3, 4) : "",
style: CText(
s: 24.0,
),
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 0),
child: TextField(
controller: control,
textAlign: TextAlign.start,
maxLength: 4,
onChanged: (value) {
setState(() {});
},
showCursor: false,
style: TextStyle(
color: Colors.transparent,
fontWeight: FontWeight.bold,
fontSize: 24,
letterSpacing: 36,
),
decoration: InputDecoration(
hintText: "",
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 30)),
// )
),
)
],
),
);
}
}