Firebase phone auth flutter crash

2020-07-03 10:49发布

问题:

When I run this code on the simulator or on a real device (iPhone SE), the app is just stopping when I press the "confirm" button. When I try to put some breakpoint in debug mode, it does not stop the app at the breakpoint. Finally, I do not get any exception during the running or even when it freezes.

So I am asking for your help, thanks in advance.

import 'dart:async';

import 'package:flutter/material.dart';

import 'package:firebase_auth/firebase_auth.dart';

import 'package:chart_test/testDeg.dart';
import 'main.dart';


class Login extends StatefulWidget {
  @override
  _LoginState createState() => new _LoginState();
}

class _LoginState extends State<Login> {
  String phoneNo;
  String smsCode;
  String verificationId;

  Future<void> verifyPhone() async {
    final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
      this.verificationId = verId;
    };

    final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
      this.verificationId = verId;
      smsCodeDialog(context).then((value) {
        print('Signed in');
      });
    };

    final PhoneVerificationCompleted verifiedSuccess = (FirebaseUser user) {
      print('verified');
    };

    final PhoneVerificationFailed veriFailed = (AuthException exception) {
      print('${exception.message}');
    };

    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: this.phoneNo,
        codeAutoRetrievalTimeout: autoRetrieve,
        codeSent: smsCodeSent,
        timeout: const Duration(seconds: 5),
        verificationCompleted: verifiedSuccess,
        verificationFailed: veriFailed);
  }

  Future<bool> smsCodeDialog(BuildContext context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text('Enter sms Code'),
            content: TextField(
              keyboardType: TextInputType.number,
              onChanged: (value) {
                this.smsCode = value;
              },
            ),
            contentPadding: EdgeInsets.all(10.0),
            actions: <Widget>[
              new FlatButton(
                child: Text('Done'),
                onPressed: () {
                  FirebaseAuth.instance.currentUser().then((user) {
                    if (user != null) {
                      Navigator.of(context).pop();
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => TestDeg(user.phoneNumber,key:MyApp.link)),
                      );
                    } else {
                      Navigator.of(context).pop();
                      //signIn();
                    }
                  });
                },
              )
            ],
          );
        });
  }

  signIn() {
    FirebaseAuth.instance
        .signInWithPhoneNumber(verificationId: verificationId, smsCode: smsCode)
        .then((user) {
      Navigator.of(context).pushReplacementNamed('/homepage');
    }).catchError((e) {
      print(e);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Connexion'),
      ),
      body: new Center(
        child: Container(
            padding: EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                TextField(
                  decoration: InputDecoration(hintText: 'number'),
                  onChanged: (value) {
                    this.phoneNo = value;
                  },
                ),
                SizedBox(height: 10.0),
                RaisedButton(
                    onPressed: verifyPhone,
                    child: Text('Confirm'),
                    textColor: Colors.white,
                    elevation: 7.0,
                    color: Colors.blue)
              ],
            )),
      ),
    );
  }
}

First throw call stack:

(
0   CoreFoundation                      0x00000001075521e6 __exceptionPreprocess + 294
1   libobjc.A.dylib                     0x00000001066ab031 objc_exception_throw + 48
2   CoreFoundation                      0x00000001075c7975 +[NSException raise:format:] + 197
3   Runner                              0x000000010246a5db -[FIRPhoneAuthProvider verifyPhoneNumber:UIDelegate:completion:] + 187
4   Runner                              0x00000001027e11af -[FLTFirebaseAuthPlugin handleMethodCall:result:] + 13919
5   Flutter                             0x00000001041defe3 __45-[FlutterMethodChannel setMethodCallHandler:]_block_invoke + 118
6   Flutter                             0x00000001041f90d0 _ZNK5shell21PlatformMessageRouter21HandlePlatfor<…>
Lost connection to device.
Exited (sigterm)

回答1:

You need to add the Firebase url scheme to your Info.plist. Go to <app_directory>/ios/Runner/Info.plist and add the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    ...

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <!-- Insert your reversed client ID here -->
                <string> REVERSED_CLIENT_ID </string>
            </array>
        </dict>
    </array>

    ...
</dict>
</plist>

You can get the REVERSED_CLIENT_ID from your GoogleService-Info.plist file.

You can find more information here.