flutter - 在不同的小部件之间共享回调
问题描述
我在我的 Flutter 应用程序中使用 FirebaseAuth。我正在尝试使用电话号码进行验证。这个想法是有一个页面供用户输入电话号码,另一个页面用于验证 SMS 代码。
这是我写的:
FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
verificationCompleted:
(PhoneAuthCredential credential) {},
verificationFailed: (FirebaseAuthException e) {
showError(
context: context,
firebaseAuthException: e,
);
},
codeSent: (String verificationId, int resendToken) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CodeVerification(
verificationId: verificationId,
resendToken: resendToken,
authHandler: authHandler,
)),
);
},
codeAutoRetrievalTimeout: (String verificationId) {},
);
但是当我将另一个小部件 ( CodeVerification
) 推送到 时Navigator
,我不知道第二个小部件中的verificationFailed
和verificationCompleted
回调。
解决此问题的最佳方法是什么?
解决方案
为什么需要将 Navigator 推送到另一条路线?您不能创建一个完全管理电话身份验证的单一路由吗?当回调触发您将其设置为 true时,我将创建一个有状态的小部件,bool
以便显示/隐藏代码输入。codeSent
遵循未经测试的示例:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class PhoneAuthenticationScreen extends StatefulWidget {
final String phoneNumber;
const PhoneAuthenticationScreen({Key key, this.phoneNumber}) : super(key: key);
@override
_PhoneAuthenticationScreenState createState() => _PhoneAuthenticationScreenState();
}
class _PhoneAuthenticationScreenState extends State<PhoneAuthenticationScreen> {
final _codeTextFieldController = TextEditingController();
bool showCodeInput = false;
String verificationId;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
buildSendCodeButton(),
buildCodeInput(),
],
),
);
}
buildSendCodeButton() {
return RaisedButton(
child: Text("send code"),
onPressed: () {
FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: widget.phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) {},
verificationFailed: (FirebaseAuthException e) {},
codeSent: (String verificationId, int resendToken) {
setState(() {
showCodeInput = true;
verificationId = verificationId;
});
},
codeAutoRetrievalTimeout: (String verificationId) {},
);
},
);
}
buildCodeInput() {
if (!showCodeInput) return Container();
return Row(
children: [
TextField(
controller: _codeTextFieldController,
),
RaisedButton(
child: Text("Submit"),
onPressed: () async {
final smsCode = _codeTextFieldController.text;
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: smsCode);
await FirebaseAuth.instance.signInWithCredential(phoneAuthCredential);
},
)
],
);
}
}
推荐阅读
- android - Flutter:同时使用 Pan 和 Scale 手势?
- python - Mongoengine 检查连接是否成功
- flutter - 在富文本颤动中使用图标时,如何垂直对齐图标
- python - 在哪里查看 Swarm 负载均衡器日志?
- javascript - 根据 Flask 微服务的进度创建 React JS 进度条?
- java - 使用 Java-8 对数组中的数字进行排序而不更改偶数位置
- julia - 在 Julia 中使用 NTuple 参数类型与使用抽象向量
- awk - 如何拒绝以awk中的某些文本开头的字符串?
- regex - regexp 语句中没有前面的字符
- mysql - 如何从 MySQL 查询中的电子邮件地址中删除“加号”标签?