Автозаполнение SMS не работает во Flutter, несмотря на доступ для чтения и полученияAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Автозаполнение SMS не работает во Flutter, несмотря на доступ для чтения и получения

Сообщение Anonymous »

Я работаю над реализацией автозаполнения SMS с помощью пакета sms_autofill в своем приложении Flutter. Несмотря на предоставление необходимых разрешений на чтение и получение 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 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
 createState() => _PhoneNumberTextFieldState();
}

class _PhoneNumberTextFieldState extends State
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?
  • Что может быть причиной ошибки «Чтение пустой строки здесь не поддерживается»?
  • Как правильно реализовать автозаполнение SMS для обработки OTP во Flutter?


Подробнее здесь: https://stackoverflow.com/questions/791 ... ive-access
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»