1

Error : I am getting below error in Stream while mapping

The argument type 'UserModel? Function(User)' can't be assigned to the parameter type 'UserModel Function(User?)' The code and the directories

-user.dart

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

-auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_login/models/user.dart';
import 'package:flutter/cupertino.dart';

//Create UserModel Object

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

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // auth change user stream
  Stream<UserModel> get users{
    return _auth.authStateChanges().map(_userFromFireBase);
  }

  //sign-in method
  Future signInAnon() async{
    try{
      UserCredential result = await _auth.signInAnonymously();
      User? user = result.user;
      return _userFromFireBase(user!);
    }catch(e){
      print(e.toString());
      return null;


}
  • Welcome to StackOverflow! Please read [how to write a good question](https://stackoverflow.com/help/how-to-ask). Have you read documentation about null safety in Dart? – Peter Koltai Aug 18 '21 at 06:37

1 Answers1

1

change

UserModel? _userFromFireBase(User user){
  return user != null ? UserModel(uid: user.uid) : null;
}

to

UserModel? _userFromFireBase(User? user){
  return user != null ? UserModel(uid: user.uid) : null;
}

The _userFromFireBase user in your code is nullable yet the User object you are passing in is not. Make it nullable by adding the ? after your User class name like User? user and it will work

SKS81
  • 117
  • 2
  • 13