error: The argument type 'UserModel? Function(User?)' can't be assigned to the parameter type 'UserModel Function(User?)' - flutter

I am getting the following error in flutter.
UserModel is a class
class UserModel {
final String uid;
UserModel({this.uid});
}
And the code where this error is coming up is
Stream<UserModel> get user {
return _auth.authStateChanges()
.map(_userFromFirebaseUser);
}
Complete code:
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
UserModel? _userFromFirebaseUser(User? user) {
return user != null ? UserModel(uid: user.uid) : null;
}
Stream<UserModel> get user {
return _auth.authStateChanges()
.map(_userFromFirebaseUser);
}
Future signInAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User user = result.user!;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
Future signInWithEmailAndPassword( String email, String password) async {
try {
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User user = result.user!;
return _userFromFirebaseUser(user);
} catch(e){
print(e.toString());
return null;
}
}
Future signUpWithEmailAndPassword( String email, String password) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
User user = result.user!;
return _userFromFirebaseUser(user);
} catch(e){
print(e.toString());
return null;
}
}
Future signOut() async {
try {
return await _auth.signOut();
} catch (e){
print(e.toString());
return null;
}
}
}

This is happening because your _userFromFirebaseUser is defined something like this,
UserModel? _userFromFirebaseUser(User? user) {
So this means that you are saying, your _userFromFirebaseUser might return a UserModel or might return a null.
One way to fix this is to make your getter return Stream<UserModel?> instead of Stream<UserModel>.
Stream<UserModel?> get user {
return _auth.authStateChanges()
.map(_userFromFirebaseUser);
}
Now your getter might return a UserModel or it might return a null.

I had the same problem and I'm glad I found the solution :
UserModel _userFromFirebase (User? user){
return UserModel(uid: user!.uid);
}
Stream<UserModel> get user{
return _auth.authStateChanges().map(_userFromFirebase);
}
and if _userFromFirebase appears error use:
_userFromFirebase(user.user) ;

Related

The argument type 'Bro? Function(Bro?)' can't be assigned to the parameter type 'Bro? Function(User?)'

auth.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:lewandowski/models/bro.dart';
import '../shared/database.dart';
class AuthService{
// method to sign in anon
final FirebaseAuth _auth = FirebaseAuth.instance;
Bro? get bro => null;
// create an object based on firebaseuser
Bro? _userfromFirebaseUser(Bro? user){
return User != null ? Bro(uid:user!.uid) : null;
}
// change user stream
Stream<Bro?> get user {
return _auth.authStateChanges().map(_userfromFirebaseUser);
}
Future signAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
return user;
}
catch (e) {
print(e.toString());
return null;
}
}
Future signInWithEmailandPassword(String email, String password) async{
try {
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User? user = result.user;
return _userfromFirebaseUser(user as Bro);
}
catch(e){
print(e.toString());
}
}// method to sign in with email and password
// method to sign up with email and password
Future registerWithEmailandPassword(String email, String password) async{
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
// use of brewscollection
await DatabaseService(uid: user!.uid).updateDatabase('0', 'new user', 100);
return _userfromFirebaseUser(user as Bro);
}
catch(e){
print(e.toString());
}
}
//method to sign out
Future signOut() async{
try{
return await _auth.signOut();
}
catch(e){
print(e.toString());
}
return null;
}
}
error on:
Stream<Bro?> get user {
return _auth.authStateChanges().map(_userfromFirebaseUser);
says:The argument type 'Bro? Function(Bro?)' can't be assigned to the parameter type 'Bro? Function(User?)'.
Running Gradle task 'assembleDebug'...
lib/services/auth.dart:20:41: Error: The argument type 'Bro? Function(Bro?)' can't be assigned to the parameter type 'Bro? Function(User?)'.
- 'Bro' is from 'package:lewandowski/models/bro.dart' ('lib/models/bro.dart').
- 'User' is from 'package:firebase_auth/firebase_auth.dart' ('../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_auth-3.9.0/lib/firebase_auth.dart').
return _auth.authStateChanges().map(_userfromFirebaseUser);
^
FAILURE: Build failed with an exception.
The value from _auth.authStateChanges() will be User But you are expecting Bro.
Try changing the function parameter type from Bro? to User?
Bro? _userfromFirebaseUser(User? user){
return user != null ? Bro(uid:user!.uid) : null;
}

How to get data from the CurrentUser on flutter Firebase Authentification

I have this Firebase Authentication Providers with who I can create an user, Sign In and Sign Out with the methods (only with email and password)
My problem I that in the UI I want to show data from the current User once the user has Sign In and I don't know how.
For example showing the email in a TextWidget or get the email as a variable for other stuff.
final firebaseAuthProvider = Provider<FirebaseAuth>((ref) {
return FirebaseAuth.instance;
});
class AuthenticationService {
final FirebaseAuth _firebaseAuth;
final Reader read;
AuthenticationService(this._firebaseAuth, this.read);
Stream<User?> get authStateChange => _firebaseAuth.authStateChanges();
Future<String> signIn({required String email, required String constrasena, required String nombreUsuario}) async {
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: constrasena,
);
return "Login Successful";
} on FirebaseAuthException catch (e) {
return e.message ?? 'Error';
}
}
Future<String> signUp({required String email, required String constrasena, required String nombreUsuario}) async {
try {
await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: constrasena,
);
read(addPerson(Person(nombre_de_usuario: nombreUsuario, email: email, videosVistos: 0)));
return "Signup Successful";
} on FirebaseAuthException catch (e) {
print(e.message);
return e.message ?? 'Error';
}
}
Future<void> signout() async {
await _firebaseAuth.signOut();
}
}
final authServicesProvider = Provider<AuthenticationService>((ref) {
return AuthenticationService(ref.read(firebaseAuthProvider), ref.read);
});
final authStateProvider = StreamProvider<User?>((ref) {
return ref.watch(authServicesProvider).authStateChange;
});
Thanks You!
You can use FirebaseAuth.instance.currentUser.
Example:
Get the user on your initState.
_user = FirebaseAuth.instance.currentUser;
And on your build method:
Text(_user?.email ?? 'No email')

A value of type 'Stream<User?>' can't be returned from the function 'user' because it has a return type of 'Stream<User>?'

I am getting red line on auth.authStateChanges(),
Error says : A value of type 'Stream<User?>' can't be returned from the function 'user' because it has a return type of 'Stream?'.
class Auth {
final FirebaseAuth auth;
Auth({required this.auth});
Stream<User>? get user => auth.authStateChanges(); <-- here
Update now i get this error:
Future<String?> createAccount({required String email, required String password}) async {
try {
await auth.createUserWithEmailAndPassword( <-- here **auth**
email: email.trim(),
password: password.trim(),
);
return "Success";
} on FirebaseAuthException catch (e) {
return e.message;
} catch (e) {
rethrow;
}
}
Here is your updated class
import 'package:firebase_auth/firebase_auth.dart';
class Auth {
final FirebaseAuth auth;
Auth({required this.auth});
Stream<User?> get user => auth.authStateChanges();
Future<String?> createAccount({required String email, required String password}) async {
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email.trim(),
password: password.trim(),
);
return "Success";
} on FirebaseAuthException catch (e) {
return e.message;
} catch (e) {
rethrow;
}
}
}

Why it is showing -- "The argument type 'User' can't be assigned to the parameter type 'User1' in flutter"

I get the below error when I run the code, Pls help me
error: The argument type 'User' can't be assigned to the parameter type 'User1'. (argument_type_not_assignable at [time_tracker_app] lib\services\auth.dart:34)
here is my code :
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
class User1 {
User1({#required this.uid, });
final String uid;
}
abstract class AuthBase {
Future<User1> currentUser();
Future<User1> signInAnonymously();
Future<void> signOut();
}
class Auth implements AuthBase {
final _firebaseAuth = FirebaseAuth.instance;
User1 _userFromFirebase(User1 user) {
if (user == null) {
return null;
}
return User1(uid: user.uid);
}
#override
Future<User1> currentUser() async {
final user = _firebaseAuth.currentUser;
return _userFromFirebase(User1(uid: user.uid));
}
#override
Future<User1> signInAnonymously() async {
final authResult = await _firebaseAuth.signInAnonymously();
return _userFromFirebase(authResult.user);
}
Future<void> signOut() async {
await _firebaseAuth.signOut();
}
}
The issue is in the _userFromFirebase function parameter. From the signInAnonymously function you are calling the _userFromFirebase function with Firebase User object.
#override
Future<User1> signInAnonymously() async {
final authResult = await _firebaseAuth.signInAnonymously();
return _userFromFirebase(authResult.user); // Passing User object
}
To fix the issue, you need to change the parameter type:
User1 _userFromFirebase(User user) {
if (user == null) {
return null;
}
return User1(uid: user.uid);
}

'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.
'UserModel' is from 'package:twitterclone/models/users.dart' ('lib/models/users.dart').
'User' is from 'package:firebase_auth/firebase_auth.dart' ('../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.0.1/lib/firebase_auth.dart').
return auth.authStateChanges().map(_userFromFirebaseUser);
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);
}
}
}
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) ...
Use This code:-
Stream<UserList?> get user {
return _auth
.authStateChanges()
.map((User? user) => _userFromFirebase(user!));
}
*UserList is class,
null safety!