Luqman Hakim
Luqman Hakim

Reputation: 31

'UserModel? Function(User)' cant be assigned to the parameter type 'UserModel Function(User?)' because 'UserModel?' is nullable and 'UserModel' isn't

#I've been following a youtube project for twitter clone and I get error when putting _userFromFirebaseUser in map();#

##I get error at time 13:29, here is the link. https://www.youtube.com/watch?v=YI7avcWI3aQ&t=919s ##

##The error that I received at the terminal is Launching lib\main.dart on sdk gphone x86 arm in debug mode... lib\main.dart:1 lib/services/auth/auth.dart:13:40: Error: The argument type 'UserModel? Function(User)' can't be assigned to the parameter type 'UserModel Function(User?)' because 'UserModel?' is nullable and 'UserModel' isn't.

The code and the directories

-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);
    }
  }
}

Upvotes: 0

Views: 1117

Answers (2)

muhsin
muhsin

Reputation: 35

Use This code:-

  Stream<UserList?> get user {
  return _auth
    .authStateChanges()
    .map((User? user) => _userFromFirebase(user!));
 }

*UserList is class,

null safety!

Upvotes: 0

faithomotoso
faithomotoso

Reputation: 454

In

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

Since UserModel is nullable, change the argument to be nullable also

UserModel? _userFromFirebaseUser(User? user) ...

Upvotes: 1

Related Questions