尽管提供了读取和接收访问权限,短信自动填充在 Flutter 中仍不起作用

问题描述 投票:0回答:1

我正在努力使用 Flutter 应用程序中的

sms_autofill
包实现短信自动填充。尽管授予了必要的读取和接收 SMS 权限,但
codeUpdated
方法并未被调用,而且我似乎无法让 OTP 自动填充工作。这是我的代码和相关日志:

代码:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:exampleapp/constants/app_colors.dart';
import 'package:sms_autofill/sms_autofill.dart';
import 'package:permission_handler/permission_handler.dart';

class PhoneNumberTextField extends StatefulWidget {
  final ValueChanged<String> valueChange;
  final int maxLength;
  final String labelText;
  final String hintText;
  final String preFix;
  final bool focus;
  final bool otpAutoFill;

  const PhoneNumberTextField({
    super.key,
    required this.valueChange,
    this.maxLength = 10,
    this.labelText = "",
    this.hintText = "Enter phone number",
    this.preFix = "+91 - ",
    this.focus = false,
    this.otpAutoFill = false,
  });

  @override
  State<PhoneNumberTextField> createState() => _PhoneNumberTextFieldState();
}

class _PhoneNumberTextFieldState extends State<PhoneNumberTextField>
    with CodeAutoFill {
  final ctrlNumber = TextEditingController();
  final FocusNode unitCodeCtrlFocusNode = FocusNode();
  bool isValidPhoneNumber = false;
  bool _isFocused = false;
  String? appSignature;

  @override
  void initState() {
    super.initState();
    if (widget.focus) {
      unitCodeCtrlFocusNode.requestFocus();
    }
    unitCodeCtrlFocusNode.addListener(() {
      if (unitCodeCtrlFocusNode.hasFocus) {
        setState(() {
          _isFocused = unitCodeCtrlFocusNode.hasFocus;
        });
      }
    });
    if (widget.otpAutoFill) {
      requestSMSPermissions();
      SmsAutoFill().listenForCode();
      print("Listening for SMS");
    }
  }

  void requestSMSPermissions() async {
    var status = await Permission.sms.status;
    if (!status.isGranted) {
      await Permission.sms.request();
    }
  }

  @override
  void codeUpdated() {
    if (widget.otpAutoFill) {
      print("Checking OTP Autofetch: $code");
      if (code != null) {
        print("Received OTP Code: $code");
        setState(() {
          ctrlNumber.text = code!;
          widget.valueChange(code!);
        });
      } else {
        print("No code received or code is empty");
      }
    }
  }

  @override
  void dispose() {
    SmsAutoFill().unregisterListener();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      focusNode: unitCodeCtrlFocusNode,
      controller: ctrlNumber,
      enableInteractiveSelection: true,
      cursorColor: AppColors.colorTextPrimary,
      style: const TextStyle(
        color: AppColors.colorTextPrimary,
        fontWeight: FontWeight.w400,
        fontSize: 16,
      ),
      validator: (val) {
        if (val == null || val.isEmpty) {
          return 'Please Enter some text';
        } else if (val.length < 10) {
          return 'Invalid phone number';
        } else {
          return null;
        }
      },
      onChanged: (value) {
        widget.valueChange(value);
        if (value.length >= widget.maxLength) {
          setState(() {
            isValidPhoneNumber = true;
          });
        } else {
          if (isValidPhoneNumber) {
            setState(() {
              isValidPhoneNumber = false;
            });
          }
        }
      },
      maxLength: widget.maxLength,
      keyboardType: TextInputType.phone,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp("[0-9]")),
      ],
      decoration: InputDecoration(
        contentPadding: const EdgeInsets.all(0.0),
        border: const UnderlineInputBorder(
          borderSide: BorderSide(
            color: AppColors.colorAccentSwatch,
            width: 0.0,
          ),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: widget.preFix != ""
                ? AppColors.colorAccentSwatch
                : AppColors.lightGrey,
            width: 1.0,
          ),
        ),
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(
            color: Color.fromARGB(255, 205, 204, 204),
            width: 1.0,
          ),
        ),
        isDense: false,
        prefixText: _isFocused ? widget.preFix : "",
        counterText: '',
        labelText: widget.labelText,
        labelStyle: const TextStyle(
          color: AppColors.colorAccentSwatch,
        ),
        hintText: widget.hintText,
        hintStyle: const TextStyle(fontWeight: FontWeight.w500),
      ),
    );
  }
}

问题: codeUpdated 方法不起作用,我收到以下日志:

Listening for SMS
E/Parcel  (7639): Reading a NULL string not supported here.
666208 is your OTP for logging in to your ExampleApp account. 0cADsNfJSu - ExampleApp
  • 为什么 codeUpdated 没有被调用?
  • 可能导致“此处不支持读取 NULL 字符串”错误的原因是什么?
  • 如何在 Flutter 中正确实现短信自动填充来处理 OTP?
android flutter package
1个回答
0
投票

来自 otp sms 和 appSignature 的 Hach 代码必须相同。

© www.soinside.com 2019 - 2024. All rights reserved.