'用户模型? Function(User)' 不能分配给参数类型 'UserModel Function(User?)' 因为 'UserModel?'可以为空并且“UserModel”不是 代码和目录

问题描述

#我一直在关注 twitter 克隆的 youtube 项目,但在将 _userFromFirebaseUser 放入 map() 时出现错误;#

##我在 13:29 出现错误,这是链接https://www.youtube.com/watch?v=YI7avcWI3aQ&t=919s ##

##我在终端收到的错误在调试模式下在 sdk gphone x86 arm 上启动 lib\main.dart... lib\main.dart:1 lib/services/auth/auth.dart:13:40: 错误:参数类型“usermodel?无法将 Function(User)' 分配给参数类型 'usermodel Function(User?)',因为 'usermodel?'可以为空,而“usermodel”则不能。

  • usermodel”来自“package:twitterclone/models/users.dart”(“lib/models/users.dart”)。
  • 'User' 来自 'package:firebase_auth/firebase_auth.dart' ('../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.0.1/lib/firebase_auth 。镖')。 返回 auth.authStateChanges().map(_userFromFirebaseUser);

代码和目录

-users.dart

class usermodel {
 final String id;
 usermodel({required this.id});
}

-auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:twitterclone/models/users.dart';

class AuthService {
 FirebaseAuth auth = FirebaseAuth.instance;

  usermodel? _userFromFirebaseUser(User user) {
  // ignore: unnecessary_null_comparison
     return user != null ? usermodel(id: user.uid) : null;
  }

  Stream<usermodel> get user {
    return auth.authStateChanges().map(_userFromFirebaseUser);
  }

  Future<void> signUp(email,password) async {
    try {
      User user = (await auth.createuserWithEmailAndPassword(
          email: email,password: password)) as User;
      _userFromFirebaseUser(user);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> signIn(email,password) async {
    try {
      User user = (await auth.signInWithEmailAndPassword(
          email: email,password: password)) as User;

      _userFromFirebaseUser(user);
    } on FirebaseAuthException catch (e) {
      print(e);
    } catch (e) {
      print(e);
    }
  }
}

解决方法

UserModel? _userFromFirebaseUser(User user) {
  // ignore: unnecessary_null_comparison
     return user != null ? UserModel(id: user.uid) : null;
  }

由于 UserModel 可以为空,因此将参数也更改为可以为空

UserModel? _userFromFirebaseUser(User? user) ...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...