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;
}
Related
Flutter is not writing data to my firebase collection and has errors in the debug.
Steps to reproduce
https://www.youtube.com/watch?v=EA7973HI93E&list=PL4cUxeGkcC9j--TKIdkb3ISfRbJeJYQwC&index=18
Steps to reproduce the behavior:
Run the app,
register a user.
Expected behavior:
I expected that the user will be made and data to the collection added
the output
Ignoring header X-Firebase-Locale because its value was null. D/FirebaseAuth(17181): Notifying id token listeners about user ( fTnXUNwmPUajE9ybOeP3GLW0e392 ). D/FirebaseAuth(17181): Notifying auth state listeners about user ( fTnXUNwmPUajE9ybOeP3GLW0e392 ). W/DynamiteModule(17181): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found. I/DynamiteModule(17181): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0 W/ProviderInstaller(17181): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0. W/Firestore(17181): (24.4.0) [WriteStream]: (e9a00e8) Stream closed with status: Status{code=UNAVAILABLE, description=Channel shutdownNow invoked, cause=null}. W/DynamiteModule(17181): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
my auth.dart code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:my_app/models/user.dart';
import 'package:my_app/services/database.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// create MyUser object based on User
MyUser? _userFromFirebaseUser(User? user) {
return user != null ? MyUser(uid: user.uid) : null;
}
// auth change user stream
Stream<MyUser?> get user {
return _auth.authStateChanges().map(_userFromFirebaseUser);
}
//sign in anonymously
Future signInAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
// sign in with email and password
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;
}
}
// register 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;
// create new document for the user with uid
await DatabaseService(uid: user?.uid)
.updateUserData('How do you feel', 'I am mad', 'angry');
return _userFromFirebaseUser(user);
} on FirebaseAuthException catch (e) {
print(e.toString());
return null;
}
}
// sign out
Future signOut() async {
try {
return await _auth.signOut();
} catch (e) {
print(e.toString());
return null;
}
}
}
My database.dart
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseService {
// collection reference
final String? uid;
DatabaseService({this.uid});
final CollectionReference pollearnCollection =
FirebaseFirestore.instance.collection('Pollearn');
Future updateUserData(String question, String answer, String emotion) async {
Map<String, String> data = {
'question': question,
'answer': answer,
'emotion': emotion,
};
return await pollearnCollection.doc(uid).set(data);
}
}
I already tried the following:
turn the emulator on and off.
tried different emulator
updated google play services
turnt bluetooth off
turnt internet off and on
enabled sign in with mail and password
adding
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I hope you guys can help me. Thanks in advance!
The argument type 'CurrentUser? Function(User)' can't be assigned to the parameter type 'CurrentUser Function(User?)'.dartargument_type_not_assignable
CurrentUser? _userFromFirebase(User user)
package:brew_crew/services/auth.dart
im getting this error i was creating anonimouse user login on flutter firebase
can any help me out..
code is below
// Create user object based on FirebaseUser
CurrentUser? _userFromFirebase(User user) {
return user != null ? CurrentUser (uid: user.uid) : null;
}
// auth change obj stream
Stream<CurrentUser> get users{
return _auth.authStateChanges().map(_userFromFirebase);
}
full code is here
import 'package:brew_crew/model/user.dart';
import 'package:firebase_auth/firebase_auth.dart';
class AuthService{
final FirebaseAuth _auth = FirebaseAuth.instance;
// Create user object based on FirebaseUser
CurrentUser? _userFromFirebase(User user) {
return user != null ? CurrentUser (uid: user.uid) : null;
}
// auth change obj stream
Stream<CurrentUser> get users{
return _auth.authStateChanges().map(_userFromFirebase);
}
//sin in anon
Future signInAnon() async{
try {
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
return _userFromFirebase(user!);
}catch (e) {
print(e.toString());
return null;
}
}
//sign in with E-mail and password
//Register with E-mail and passqord
//Sign out
}
thanks
You can just change your Stream type to CurrentUser?:
CurrentUser? _userFromFirebase(User user) {
return user != null ? CurrentUser (uid: user.uid) : null;
}
// v
Stream<CurrentUser?> get users{
return _auth.authStateChanges().map(_userFromFirebase);
}
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) ;
#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!
Register Screen On Pressed method given, I believe there is a problem with calling Firebase user = result.user
onPressed: () async {
if(_formKey.currentState.validate()){
setState(() => loading = true);
dynamic result = await _auth.registerWithEmailAndPassword(email, password);
FirebaseUser user = result.user;
await DatabaseService(uid: user.uid).newUserInfo(
_nameC.text,
_cityC.text,
_contactnoC.toString()
);
if(result == null) {
setState(() {
error = 'Please supply a valid email';
loading = false;
});
}}},
// Database backend
class DatabaseService {
final String uid;
DatabaseService ({this.uid});
final CollectionReference userdata2 = Firestore.instance.collection('UserData');
Future newUserInfo(String name, String city, String contactno) async {
return await userdata2.document(uid).setData({
'name' : name,
'city' : city,
'contactno' : contactno
});
}}
// authentication backend
// register with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
DatabaseService(uid: user.uid);
return _userFromFirebaseUser(user);
} catch (error) {
print(error.toString());
return null;
} }
// user.dart
class User {
final String uid;
User({this.uid});
}