以下是一个简化的Flutter应用程序,用于创建一个类似于Boss直聘App的4位数短信验证码输入界面。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('短信验证码'),
),
body: PinCodeScreen(),
),
);
}
}
class PinCodeScreen extends StatefulWidget {
@override
_PinCodeScreenState createState() => _PinCodeScreenState();
}
class _PinCodeScreenState extends State<PinCodeScreen> {
List<String> _smsCode = [];
void _submitPinCode() {
// 验证并处理短信码
print('验证码提交: ${_smsCode.join()}');
}
void _onSmsCodeChanged(int index, String value) {
setState(() {
if (value.isNotEmpty) {
// 当输入框有值时更新列表
if (_smsCode.length == index) {
_smsCode.add(value);
} else {
_smsCode[index] = value;
}
} else if (index < _smsCode.length) {
// 当输入框清空时移除列表中的值
_smsCode.removeAt(index);
}
});
if (index == 3) {
_submitPinCode();
}
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
for (int i = 0; i < 4; i++)
PinCodeBox(
onChanged: (value) => _onSmsCodeChanged(i, value),
),
Spacer(),
RaisedButton(
child: Text('提交'),
onPressed: _smsCode.length == 4 ? _submitPinCode : null,
),
],
);
}
}
class PinCodeBox extends StatefulWidget {
final ValueChanged<String> onChanged;
PinCodeBox({this.onChanged});
@override
_PinCodeBoxState createState() => _PinCodeBoxState();
}
class _PinCodeBoxState extends State<PinCodeBox> {
TextEditingController _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4.0),
),
child: TextField(
controller: _controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
style: