dart OTPTextField:用于空值的空检查运算符

1bqhqjot  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(133)

我正在使用otp_text_field: ^1.1.3在Flutter应用程序中通过PIN码验证电子邮件。如果我尝试在输入框中输入第一个值,应用程序会因异常而崩溃。
应用程序UI:

代码编辑器:

验证码:

import 'package:flutter/material.dart';
import 'package:flutter_countdown_timer/flutter_countdown_timer.dart';
import 'package:otp_text_field/otp_field.dart';
import 'package:otp_text_field/otp_text_field.dart';
import 'package:otp_text_field/style.dart';

...

class OTPPage extends StatefulWidget {
  SingInController con;
  OTPPage(this.con);
  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<OTPPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Theme.of(context).backgroundColor,
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Theme.of(context).backgroundColor,
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(
              height: 50,
            ),
            HeaderTxtWidget(
              'Enter the code from your email',
              fontSize: 16,
            ),
            const SizedBox(
              height: 20,
            ),
            Center(
              child: OTPTextField(
                length: 4,
                width: MediaQuery.of(context).size.width - 50,
                fieldWidth: 50,
                style: const TextStyle(fontSize: 17),
                textFieldAlignment: MainAxisAlignment.spaceAround,
                fieldStyle: FieldStyle.box,
                outlineBorderRadius: 10,
                onCompleted: (pin) {
                  widget.con.OTP = pin;
                },
              ),
            ),
            ...
          ],
        ));
  }
}

添加了更好的代码,而不是屏幕截图。请让我知道解决方案。谢谢你!!

0dxa2lsx

0dxa2lsx1#

为了避免错误,需要包含onChanged:(s){}回调,即使您不打算使用它。如果没有此回调,onChange属性将为null,并将发生错误。

OTPTextField(
                length: 4,
                width: MediaQuery.of(context).size.width - 50,
                fieldWidth: 50,
                style: const TextStyle(fontSize: 17),
                textFieldAlignment: MainAxisAlignment.spaceAround,
                fieldStyle: FieldStyle.box,
                outlineBorderRadius: 10,
                onChanged: (val) {},
                onCompleted: (pin) {
                  widget.con.OTP = pin;
                },
              )

相关问题