Firebase 如何访问未来方法| Dart中存在的回调函数的返回值

Firebase 如何访问未来方法| Dart中存在的回调函数的返回值,firebase,flutter,dart,firebase-authentication,Firebase,Flutter,Dart,Firebase Authentication,验证省道 class AuthService { final FirebaseAuth _auth = FirebaseAuth.instance; // Sign in with Phone Number Future<bool> Future signInWithPhone(String phone, BuildContext context) async { final PhoneVerificationCompleted verificationCo

验证省道

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Sign in with Phone Number Future<bool>
  Future signInWithPhone(String phone, BuildContext context) async {

    final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) async {
      ..
    };

    final PhoneVerificationFailed verificationFailed = (AuthException exception) {
      // This is the return value which i want to access outside of this callback
      return exception.message;
    };

    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) {
        ...
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) {
        Navigator.of(context).pop();
        ...
    };

    await _auth.verifyPhoneNumber(
      phoneNumber: phone,
      timeout: Duration(seconds: 10),
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,        
      codeSent: codeSent,
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout
    );

    // Trying to access the callback value
    print(verificationFailed);
 }
}
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  @override
  Widget build(BuildContext context) {
    return Container(

     // here i am calling the phonesign in method
      await _auth.signInWithPhone(phoneNumber, context);

     // and here i want to show the message

    );
  }

}
类身份验证服务{
final FirebaseAuth _auth=FirebaseAuth.instance;
//使用未来的电话号码登录
未来登录WithPhone(字符串电话、BuildContext上下文)异步{
最终电话验证已完成验证已完成=(AuthCredential凭据)异步{
..
};
最终电话验证失败验证失败=(AuthException异常){
//这是我希望在此回调之外访问的返回值
返回异常消息;
};
final PhoneCodeSent=(字符串验证ID,[int-forceResendingToken]){
...
};
最终PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout=(字符串验证ID){
Navigator.of(context.pop();
...
};
等待_auth.verifyPhoneNumber(
电话号码:电话,
超时:持续时间(秒:10),
验证完成:验证完成,
验证失败:验证失败,
codeSent:codeSent,
codeAutoRetrievalTimeout:codeAutoRetrievalTimeout
);
//正在尝试访问回调值
打印(验证失败);
}
}
login.dart

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Sign in with Phone Number Future<bool>
  Future signInWithPhone(String phone, BuildContext context) async {

    final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) async {
      ..
    };

    final PhoneVerificationFailed verificationFailed = (AuthException exception) {
      // This is the return value which i want to access outside of this callback
      return exception.message;
    };

    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) {
        ...
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) {
        Navigator.of(context).pop();
        ...
    };

    await _auth.verifyPhoneNumber(
      phoneNumber: phone,
      timeout: Duration(seconds: 10),
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,        
      codeSent: codeSent,
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout
    );

    // Trying to access the callback value
    print(verificationFailed);
 }
}
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  @override
  Widget build(BuildContext context) {
    return Container(

     // here i am calling the phonesign in method
      await _auth.signInWithPhone(phoneNumber, context);

     // and here i want to show the message

    );
  }

}
class LoginPage扩展StatefulWidget{
@凌驾
_LoginPagentate createState()=>_LoginPagentate();
}
类_loginpagentate扩展状态{
@凌驾
小部件构建(构建上下文){
返回容器(
//这里我调用电话登录方法
使用电话(电话号码、上下文)等待授权登录;
//在这里,我想展示这条信息
);
}
}
有什么问题吗?

问题是我想访问verifyPhoneNumber的任何回调的值,例如verificationFailed,它返回一条异常消息,我想在外部访问它,以便我可以在其他小部件中使用它

到目前为止我尝试了什么?

1) 我已尝试打印它,但它返回AuthException Closure:()=>String我不知道如何访问该值

2) 我尝试过使用setState,但由于我的类不在statefulWidget中,因此无法将该值赋给变量

*我为什么需要它*


看,我有两个页面,一个叫做
login.dart
,第二个叫做
auth.dart
。在我的auth页面中,我主要放置与后端相关的类和代码(以正确组织代码),在登录页面中,我有一个有状态的小部件,考虑到电话文本字段,在提交时,我使用电话调用方法signInWithPhone。一切正常,但如果出现任何错误,例如错误的用户电话号码格式,则会触发验证失败回叫,因此我希望访问外部的返回值(bcz我们无法直接获取返回值)这样我就可以从我叫它的地方看出来


任何人都可以帮助我继续我的代码。

我建议您将小部件设置为有状态,然后您可以执行以下操作:

final PhoneVerificationFailed verifiFailed = (AuthException exception) {
  setState(() {
    errorMessage = exception.message;
  });

  print('${exception.message}');
};
很容易将小部件切换为有状态:

class LoginPage extends StatefulWidget {

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {

   return Column(children: [
       ...
       errorMessage == null ? SizedBox() : Text( errorMessage),
       ...
   ]);
  }
}
class LoginPage扩展StatefulWidget{
@凌驾
_LoginPagentate createState()=>_LoginPagentate();
}
类_loginpagentate扩展状态{
@凌驾
小部件构建(构建上下文){
返回列(子项:[
...
errorMessage==null?SizedBox():文本(errorMessage),
...
]);
}
}
当errorMessage在setState内更新时,错误消息将出现

您也可以使用提供者;以下是一些供您查找的链接:


我建议您将小部件设置为有状态,然后您可以执行以下操作:

final PhoneVerificationFailed verifiFailed = (AuthException exception) {
  setState(() {
    errorMessage = exception.message;
  });

  print('${exception.message}');
};
很容易将小部件切换为有状态:

class LoginPage extends StatefulWidget {

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {

   return Column(children: [
       ...
       errorMessage == null ? SizedBox() : Text( errorMessage),
       ...
   ]);
  }
}
class LoginPage扩展StatefulWidget{
@凌驾
_LoginPagentate createState()=>_LoginPagentate();
}
类_loginpagentate扩展状态{
@凌驾
小部件构建(构建上下文){
返回列(子项:[
...
errorMessage==null?SizedBox():文本(errorMessage),
...
]);
}
}
当errorMessage在setState内更新时,错误消息将出现

您也可以使用提供者;以下是一些供您查找的链接:


现在很清楚你想做什么。使用Provider是一种方法。另一种方法是将回调传递到登录页面:

class LoginPage extends StatefulWidget {
      final Function(String) verificationMessage;

      const LoginPage({Key key, this.verificationMessage}) : super(key: key);

     @override
     _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
    …
    …
    final PhoneVerificationFailed verificationFailed = (AuthException exception) {

       widget.verificationMessage(exception.message);’
    };
}
就你而言:

飞镖

class AuthService {

  **final Function(String) verificationMessage;**
  **AuthService({@required this.verificationMessage});**

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Sign in with Phone Number Future<bool>
  Future signInWithPhone(String phone, BuildContext context) async {

    final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) async {
      ..
    };

    final PhoneVerificationFailed verificationFailed = (AuthException exception) {
      // This is the return value which i want to access outside of this callback
       **verificationMessage(exception.message);**
    };

    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) {
        ...
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) {
        Navigator.of(context).pop();
        ...
    };

    await _auth.verifyPhoneNumber(
      phoneNumber: phone,
      timeout: Duration(seconds: 10),
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,        
      codeSent: codeSent,
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout
    );

    // Trying to access the callback value
    print(verificationFailed);
 }
}
类身份验证服务{
**最终函数(字符串)验证消息**
**AuthService({@required this.verificationMessage})**
final FirebaseAuth _auth=FirebaseAuth.instance;
//使用未来的电话号码登录
未来登录WithPhone(字符串电话、BuildContext上下文)异步{
最终电话验证已完成验证已完成=(AuthCredential凭据)异步{
..
};
最终电话验证失败验证失败=(AuthException异常){
//这是我希望在此回调之外访问的返回值
**验证消息(exception.message)**
};
final PhoneCodeSent=(字符串验证ID,[int-forceResendingToken]){
...
};
最终PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout=(字符串验证ID){
Navigator.of(context.pop();
...
};
等待_auth.verifyPhoneNumber(
电话号码:电话,
超时:持续时间(秒:10),
验证完成:验证完成,
验证失败:验证失败,
codeSent:codeSent,
codeAutoRetrievalTimeout:codeAutoRetrievalTimeout
);
//正在尝试访问回调值
打印(验证失败);
}
}
login.dart

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  String message = "";

  @override
  Widget build(BuildContext context) {
    return Container(
         child: Column( 
          children: [
            Text(message),
            Flatbutton(
              .... 
              onPressed: (){
               AuthService(verificationMessage: (String newMessage) => {
                 setState(() {
                   message = newMessage
                 })
               })
              }
            )
          ]
         )
    );
  }



}
class LoginPage扩展StatefulWidget{
@凌驾
_LoginPagentate createState()=>\u LoginPage