Home > other >  How do I fix this flutter/firebase authentication problem?
How do I fix this flutter/firebase authentication problem?

Time:07-20

I get the error: The argument type 'MyUser? Function(User?, String)' can't be assigned to the parameter type 'MyUser? Function(User?)'

Auth.dart: RED LINE are under "_userFromFirebaseUser"

import 'package:firebase_auth/firebase_auth.dart';
import 'package:hyttekos/models/user.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  //MyUser Function(User? event, String name)? get userFromFirebaseUser => null;

  // create user obj
  MyUser? _userFromFirebaseUser(User? user, String name) {
    // ignore: unnecessary_null_comparison
    return user != null ? MyUser(uid: user.uid, groupId: '', name: name) : null;
  }

  // auth change user stream
  Stream<MyUser?> get user {
    return _auth.authStateChanges().map(_userFromFirebaseUser); **RED LINE are under "_userFromFirebaseUser"**
  }

  // sign in anon
  Future signInAnon(String username) async {
    try {
      UserCredential userCredidential = await _auth.signInAnonymously();
      User? user = userCredidential.user;

      return _userFromFirebaseUser(user!, username);
    } catch (e) {
      // ignore: avoid_print
      print(e.toString());
      return null;
    }
  }
}

User.dart:

class MyUser {
  final String uid;
  final String name;
  String groupId;

  MyUser({
    required this.uid,
    required this.name,
    required this.groupId,
  });
}

CodePudding user response:

On _auth.authStateChanges().map(x) here it only provides user, therefor you can't use _userFromFirebaseUser(User? user, String name). You can get name from user like user.displayName

 MyUser? _userFromFirebaseUser(User? user) {
    return user != null
        ? MyUser(uid: user.uid, groupId: '', name: user.displayName ?? "")
        : null;
  }

_auth.authStateChanges().map(_userFromFirebaseUser);

Or

  Stream<MyUser?> get user {
    return _auth.authStateChanges().map(
          (event) => _userFromFirebaseUser(event, ""),
        );
  }
  • Related