flutter & firebase :参数类型“字符串?”不能分配给参数类型“字符串”

时间:2021-06-10 19:35:35

标签: firebase flutter dart firebase-authentication

我正在为用户进行身份验证(使用 firebase)并初始化一个变量类型 String,但它不起作用,

String? _mail;
String? _password;
String? _prenom;
String? _nom;
[...]
    _handlelog(){
  if(_mail != null){
    if(_password != null){
      if(_log == true){
        //se connecter
        FirebaseHelper().handleSignIn(_mail, _password).then(((UserCredential user) {
          print("Nous avons un user");
        })).catchError((error){
          alerte(error.toString());
        });
      }else{
        if(_prenom != null){
          if(_nom != null){
            //créer un compte avec les données de l'utilisateur
            FirebaseHelper().handleCreate(_mail, _password, _prenom, _nom).then(((UserCredential user) {
              print("Nous avons pu créer un user");
            })).catchError((error){
              alerte(error.toString());
            });
          }else{
            //Alert nom
            alerte("veuillez entrer un nom pour continuer");
          }
        }else{
          //Alert prenom
          alerte("veuillez entrer un prenom pour continuer");
        }
      }
    }else{
      //Alert password
      alerte("le mot de passe est vide");
    }
  }else{
    //Alert mail
    alerte("l'adresse mail est vide");
  }
  }
[...]

我的函数FirebaseHelper()

class FirebaseHelper {

  //Authentification
  final auth = FirebaseAuth.instance;

  Future<UserCredential> handleSignIn(String mail, String password) async{
    final UserCredential credential = await auth.signInWithEmailAndPassword(email: mail, password: password);
    return credential;
  }

  Future<UserCredential> handleCreate(String mail, String password, String prenom, String nom) async{
    final UserCredential credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: mail, password: password);
    String uid = credential.user!.uid;
    Map<String, String> map = {
      "uid" : uid,
      "prenom" : prenom,
      "nom" : nom,
    };
    addUser(uid, map);
    return credential;


  }

当我使用字符串时,它的标记为:The argument type 'String?' can't be assigned to the parameter type 'String'. 代表所有 String?

1 个答案:

答案 0 :(得分:2)

String? 是可空类型,而 String 不是。

您需要使用 String 并对其进行初始化,或者创建一个从您的 String 返回 String? 的方法

例如:

String nStringToNNString(String? str) {
     return str ?? "";
}

你应该在官方文档中阅读它: Sound null safety