当前位置: 首页 > 知识库问答 >
问题:

当用户尝试登录时,它不会将其数据存储在firestore中,当我单击“确认位置”按钮时,它会显示以下错误

公冶渝
2023-03-14
class AuthProvider with ChangeNotifier {
  FirebaseAuth _auth = FirebaseAuth.instance;
String smsOtp;
String verificationId;
String error ='';
UserServices _userServices = UserServices();
bool loading = false;
LocationProvider locationData = LocationProvider();
String screen;
double latitude;
double longitude;
String address;


Future<void> verifyPhone({BuildContext context, String number}) async {
this.loading=true;
notifyListeners();
final PhoneVerificationCompleted verificationCompleted =
    (PhoneAuthCredential credential) async {
      this.loading=false;
      notifyListeners();
      await _auth.signInWithCredential(credential);
};
final PhoneVerificationFailed verificationFailed =
    (FirebaseAuthException e) {
  this.loading=false;
  print(e.code);
  this.error=e.toString();
  notifyListeners();
};
final PhoneCodeSent smsOtpSend = (String verId, int resendToken) async {
  this.verificationId = verId;
};
//open dialog to enter received OTP sms
smsOtpDialog(context, number);

try {
  _auth.verifyPhoneNumber(
      phoneNumber: number,
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,
      codeSent: smsOtpSend,
      codeAutoRetrievalTimeout: (String verId){
        this.verificationId = verId;
      },
  );
} catch (e) {
  this.error=e.toString();
  this.loading=false;
  notifyListeners();
  print(e);
}

}

Future<bool> smsOtpDialog(BuildContext context, String number) {
return showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Column(
          children: [
            Text('Verification Code'),
            SizedBox(height: 6,),
            Text('Enter 6 digits OTP received via SMS',
              style: TextStyle(color: Colors.grey,fontSize: 12),
            ),
          ],
        ),
        content: Container(
          height: 85,
          child: TextField(
            textAlign: TextAlign.center,
            keyboardType: TextInputType.number,
            maxLength: 6,
            onChanged: (value){
              this.smsOtp = value;
            },
          ),
        ),
        actions: [
          FlatButton(
          onPressed: ()async{
            try{

              PhoneAuthCredential phoneAuthCredential =
              PhoneAuthProvider.credential(
                  verificationId: verificationId, smsCode: smsOtp);

              final User user = (await _auth.signInWithCredential(phoneAuthCredential)).user;



              if(user!=null){
                this.loading=false;
                notifyListeners();

                _userServices.getUserById(user.uid).then((snapShot){
                  if(snapShot.exists){
                    //user data already exists
                    if(this.screen=='Login'){
                      //need to check user data already exists in database or not
                      //if its login,no new data, so no need to update
                      Navigator.pushReplacementNamed(context, HomeScreen.id);
                    }else{
                      //need to update new selected address
                      print('${locationData.latitude} : ${locationData.longitude}');

                      updateUser(id: user.uid, number: user.phoneNumber);
                      Navigator.pushReplacementNamed(context, HomeScreen.id);
                    }
                  }else{
                    //user data doesn't exists
                    //will create new data in db
                    _createUser(id: user.uid, number: user.phoneNumber);
                    Navigator.pushReplacementNamed(context, HomeScreen.id);

                  }
                });

              }else
                {
                  print('Login Failed');
                }
            } catch(e){
              this.error = 'Invalid OTP';
              notifyListeners();
              print(e.toString());
              Navigator.of(context).pop();
            }
          },
          child: Text('SUBMIT',style: TextStyle(color: Theme.of(context).primaryColor),),
        ),
        ],
      );
    }).whenComplete(() {
      this.loading=false;
      notifyListeners();
});

}

void _createUser({String id, String number} ) {
_userServices.createUserData({
  'id':id,
  'number':number,
  'latitude':this.latitude,
  'longitude':this.longitude,
  'address':this.address
});
this.loading=false;
notifyListeners();

}

  Future <bool> updateUser({String id, String number,} ) async{
 try{
   _userServices.updateUserData({
     'id':id,
     'number':number,
     'latitude':this.latitude,
     'longitude':this.longitude,
     'address':this.address
   });
   this.loading=false;
   notifyListeners();
   return true;

 }catch(e){
   print('Error $e');
   return false;
 }

###

======== 异常捕获的手势 =============================================================== 处理手势时抛出以下NoSuchMultiodError:getter'uid'在null上被调用。接收器: null尝试调用: uid抛出异常时,这是堆栈:#0 Object.noSuchmethod(dart: core-patch/object_patch.dart:51: 5)#1_MapScreenState.build.(包:flutter_hasho_user/屏幕/map_screen.dart:146: 44)#2_InkResponseState_handleTap(包:flutter/src/材料/ink_well.dart:993: 19)#3_InkResponseState.build.(包:flutter/src/材料/ink_well.dart:1111: 38)#4 GestureRecognizer.invokeCallback(包:flutter/src/手势/recognizer.dart:183: 24)...处理程序:“onTap”识别器: TapGesture识别器#3d7f8调试所有者: GestureDetector状态:可能赢得竞技场决赛位置:偏移(184.2, 647.6)finalLocalPoplace:偏移(164.2, 15.6)按钮: 1发送轻敲 ====================================================================================================

共有1个答案

凌征
2023-03-14

我很确定您的问题是调用。当用户为空时,else块中的用户上的uid,这会引发错误。您应该确保用户类已初始化或至少是类似的。

else{
     _createUser(id: user.uid, number: user.phoneNumber); // [user] is null
     Navigator.pushReplacementNamed(context, HomeScreen.id);

   }
 类似资料: