Flutter : how to fix Lost connection to device error with firebase PhoneNumberAuth

1,945

pop removes the top level widget. Not sure its a good idea to put logic after that. Better you re-arrange your code like

  // Only gets SMS, no functionality
  Future<String> getSmsCode(BuildContext context) {
    return showDialog<String>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('SMS 코드를 입력해주세요'),
          content: TextField(
            onChanged: (value) {
              this.smsCode = value;
            },
          ),
          contentPadding: EdgeInsets.all(10),
          actions: <Widget>[
            FlatButton(
              child: Text('Done'),
              onPressed: () {
                Navigator.of(context).pop(this.smsCode);
              },
            )
          ],
        );
      },
    );
  }


  SIGNIn() async {
    String smsCode = await getSmsCode(context);
    if (smsCode != null && !smsCode.isNotEmpty) {
      print('User cancelled SMS dialog');
      return;
    }
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    print('진행중');
    FirebaseAuth _auth = FirebaseAuth.instance;
    final FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
    final FirebaseUser currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);
    setState(() {
      if (user != null) {
        print('success!');
      } else {
        print('sign in failed');
      }
    });
  }

Now only invoke SIGNIn, it will first get SMS code then signin using that SMS code. Hope it helps.

Share:
1,945
killer whale
Author by

killer whale

Updated on December 14, 2022

Comments

  • killer whale
    killer whale over 1 year

    I am implementing phoneNumberAuth signup. But there's a problem

    When i clicked authbottom, terminated iOS app

    code :

    String smsCode, verificationId;
    
      Future<void> verifyPhone() async {
        final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
          this.verificationId = verId;
        };
    
        final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
          this.verificationId = verId;
          print('asd');
          smsCodeDialog(context).then((value) {
            print('Signed in');
          });
        };
    
        final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) {
          print('verified');
        };
    
        final PhoneVerificationFailed verfiFailed = (AuthException exception) {
          print('${exception.message}+ddddddddddd');
        };
    
        await FirebaseAuth.instance.verifyPhoneNumber(
          phoneNumber: this.phoneNo,
          timeout: const Duration(seconds: 5),
          verificationCompleted: verificationCompleted,
          verificationFailed: verfiFailed,
          codeSent: smsCodeSent,
          codeAutoRetrievalTimeout: autoRetrieve,
        );
      }
    
      Future<bool> smsCodeDialog(BuildContext context) {
        return showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('SMS 코드를 입력해주세요'),
                content: TextField(
                  onChanged: (value) {
                    this.smsCode = value;
                  },
                ),
                contentPadding: EdgeInsets.all(10),
                actions: <Widget>[
                  FlatButton(
                    child: Text('Done'),
                    onPressed: () {
                      FirebaseAuth.instance.currentUser().then((user) {
                        if (user != null) {
                          Navigator.of(context).pop();
                          Navigator.of(context).pushReplacementNamed('/');
                        } else {
                          Navigator.of(context).pop();
                          SIGNIn();
                        }
                      });
                    },
                  )
                ],
              );
            });
      }
    
    
    
      SIGNIn() async{
        final AuthCredential credential = PhoneAuthProvider.getCredential(
          verificationId: verificationId,
          smsCode: smsCode,
        );
        print('진행중');
        FirebaseAuth _auth = FirebaseAuth.instance;
        final FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
        final FirebaseUser currentUser = await _auth.currentUser();
        assert(user.uid == currentUser.uid);
        setState(() {
          if(user != null){
            print('success!');
          }else{
            print('sign in failed');
          }
        });
      }
    

    error code :

    
    *** First throw call stack:
    (
        0   CoreFoundation                      0x00000001169bb8db __exceptionPreprocess + 331
        1   libobjc.A.dylib                     0x0000000115f66ac5 objc_exception_throw + 48
        2   CoreFoundation                      0x00000001169d9c94 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
        3   CoreFoundation                      0x00000001169c0623 ___forwarding___ + 1443
        4   CoreFoundation                      0x00000001169c2418 _CF_forwarding_prep_0 + 120
        5   Runner                              0x000000010e97d966 -[FIRPhoneAuthProvider internalVerifyPhoneNumber:UIDelegate:completion:] + 118
        6   Runner                              0x000000010e97ccc0 __64-[FIRPhoneAuthProvider verifyPhoneNumber:UIDelegate:completion:]_block_invoke + 272
        7   libdispatch.dylib                   0x0000000115e16ccf _dispatch_call_block_an<…>
    Lost connection to device.
    
    

    How can i do fix my code ?

    Until someone helped me, i trying doing fix

    It's hard because there aren't many explain errors.

    I'd appreciate it if someone would help me.

    Somebody Help me :(