以下是一个简单的Flutter验证码输入框组件的实现示例:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class PinCodeTextField extends StatefulWidget {
final ValueChanged<String> onTextChanged;
final int pinLength;
const PinCodeTextField({Key? key, required this.onTextChanged, this.pinLength = 4}) : super(key: key);
@override
_PinCodeTextFieldState createState() => _PinCodeTextFieldState();
}
class _PinCodeTextFieldState extends State<PinCodeTextField> {
List<TextEditingController> _controllers = [];
List<FocusNode> _focusNodes = [];
String _pinCode = '';
@override
void initState() {
super.initState();
for (int i = 0; i < widget.pinLength; i++) {
_controllers.add(TextEditingController());
_focusNodes.add(FocusNode());
}
}
@override
void dispose() {
for (var controller in _controllers) {
controller.dispose();
}
for (var focusNode in _focusNodes) {
focusNode.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Row(
children: List.generate(
widget.pinLength,
(index) => PinCodeField(
controller: _controllers[index],
focusNode: _focusNodes[index],
onChanged: (value) {
if (index + 1 < widget.pinLength) {
FocusScope.of(context).requestFocus(_focusNodes[index + 1]);
}
_pinCode = _pinCode.substring(0, index) + value + _pinCode.substring(index + 1);
widget.onTextChanged(_pinCode);
},
textInputAction: index == widget.pinLength - 1 ? TextInputAction.done : TextInputAction.next,
onSubmitted: (value) {
if (index + 1 < widget.pinLength) {
_focusNodes[index + 1].requestFocus();
}
},
),
),
);
}
}
class PinCodeField extends StatefulWidget {
final TextEditingController controller;
final FocusNode focusNode;
final ValueChanged<String> onChanged;
final TextInputAction textInputAction;
final ValueChanged<String> onSubmitted;
const PinCodeField({
Key? key,
required this.controller,
required this.focusNode,
required this.onChanged,
required this.textInputAction,
required this.onSubmitted,
}) : super(key: key);
@override
_PinCodeFieldState createState() => _PinCodeFieldState();
}
class _PinCodeFieldS