import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class VerificationBox extends StatefulWidget {
final ValueChanged<String> onChanged;
final int length;
final String autoFillChar;
const VerificationBox({
Key? key,
required this.onChanged,
this.length = 6,
this.autoFillChar = '●',
}) : super(key: key);
@override
_VerificationBoxState createState() => _VerificationBoxState();
}
class _VerificationBoxState extends State<VerificationBox> {
final TextEditingController _controller = TextEditingController();
final FocusNode _focusNode = FocusNode();
String _pinCode = '';
@override
void initState() {
super.initState();
_controller.text = '';
_controller.addListener(() {
setState(() {
_pinCode = _controller.text;
widget.onChanged(_pinCode);
});
});
_focusNode.addListener(() {
if (!_focusNode.hasFocus) {
_controller.text = _pinCode;
}
});
}
@override
void dispose() {
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
focusNode: _focusNode,
inputFormatters: [
LengthLimitingTextInputFormatter(widget.length),
PinCodeTextInputFormatter(widget.length, widget.autoFillChar),
],
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: InputDecoration.collapsed(hintText: ''),
style: const TextStyle(fontSize: 20.0),
onChanged: (value) {},
);
}
}
class PinCodeTextInputFormatter extends TextInputFormatter {
PinCodeTextInputFormatter(this.expectedLength, this.character)
: assert(expectedLength == null || expectedLength > 0);
final int? expectedLength;
final String character;
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final newText = StringBuffer();
int textLength = 0;
for (int i = 0; i < newValue.text.length; i++) {
if (newValue.text[i] != character) {
newText.write(newValue.text[i]);
text
评论已关闭