在HarmonyOS上使用Flutter开发应用时,如果需要实现验证码输入框、跳转页面等功能,可以参考以下代码示例:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: VerificationBoxPage(),
);
}
}
class VerificationBoxPage extends StatefulWidget {
@override
_VerificationBoxPageState createState() => _VerificationBoxPageState();
}
class _VerificationBoxPageState extends State<VerificationBoxPage> {
final FocusNode _focusNode = FocusNode();
final List<TextEditingController> _controllers = [];
final _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
// 初始化验证码输入框控制器
for (int i = 0; i < 4; i++) {
_controllers.add(TextEditingController());
}
}
@override
void dispose() {
_focusNode.dispose();
for (var controller in _controllers) {
controller.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('验证码框示例'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
for (int i = 0; i < 4; i++)
Expanded(
child: TextFormField(
controller: _controllers[i],
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: i == 3 ? '请输入验证码' : '',
),
validator: (value) {
if (value.isEmpty) {
return '请输入验证码';
}
return null;
},
onFieldSubmitted: (value) {
if (i == 3) {
// 最后一个验证码输入完成后,提交表单
_submit();
} else {
// 切换到下一个