Home > other >  flutter/firebase: how to get user name from local class without quering database
flutter/firebase: how to get user name from local class without quering database

Time:10-16

Is there any way to get user properties without querying the database?

I have the following two screens:

  • sign up ( this is where I save the users info to firebase )
  • chat ( this is where I need the users information )

This is the snip of the code from the sign-up screen

// variable that calls the firebase class that holds all the logic
  late final FirebaseCloudStorage _userService;


// function that creates user 
  Future createUserAccount() async {
    if (_photo == null) return;
    try {
      setState(() {
        _isLoading = true;
      });
      await AuthService.firebase().createUser(
        email: _email.text,
        password: _password.text,
      );
      final userId = AuthService.firebase().currentUser?.id;
      final destination = 'user-profile-image/$userId';
      final ref = FirebaseStorage.instance.ref(destination);
      await ref.putFile(_photo!);
      imageUrl = await ref.getDownloadURL();
      _userService.createNewUser(
        userId: userId as String,
        userState: 'new',
        userImage: imageUrl as String,
        userFirstName: _userFirstName.text,
        userLastName: _userLastName.text,
        userCellNumber: _userCellphoneNumber.text,
        userCity: _userCity.text,
        userAreaCode: _userAreaCode.text,
        userAddress: _userAddress.text,
        userEmail: _email.text,
      );

Below is the class that has all the cloud user logic


@immutable
class CloudUser {
  final String documentId;
  final String userId;
  final String userState;
  final String userImage;
  final String userFirstName;
  final String userLastName;
  final String userCellNumber;
  final String userCity;
  final String userAreaCode;
  final String userAddress;
  final String? userEmail;

  const CloudUser({
    required this.documentId,
    required this.userId,
    required this.userState,
    required this.userImage,
    required this.userFirstName,
    required this.userLastName,
    required this.userCellNumber,
    required this.userCity,
    required this.userAreaCode,
    required this.userAddress,
    required this.userEmail,
  });


  // I TRIED CALLING THIS BUT IT DOESN'T WORK!
  // I TRIED CALLING IT FROM THE CHAT SCREEN LIKE SO:: CloudUser.getFirstName()

  String getFirstName() {
    return userFirstName;
  }

  CloudUser.fromSnapshot(QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
      : documentId = snapshot.id,
        userId = snapshot.data()[userIdColumn],
        userState = snapshot.data()[userStateColumn] ?? "",
        userImage = snapshot.data()[userImageColumn] ?? "",
        userFirstName = snapshot.data()[userFirstNameColumn] ?? "",
        userLastName = snapshot.data()[jobAreaCodeColumn] ?? "",
        userCellNumber = snapshot.data()[userCellNumberColumn] ?? "",
        userCity = snapshot.data()[userCityColumn] ?? "",
        userAreaCode = snapshot.data()[userAreaCodeColumn] ?? "",
        userAddress = snapshot.data()[userAddressColumn] ?? "",
        userEmail = snapshot.data()[userEmailColumn] ?? "";
}

class that holds logic to interact with FirebaseCloudStorage

class FirebaseCloudStorage {
  final user = FirebaseFirestore.instance.collection('user');


  Future<CloudUser> createNewUser({
    required String userId,
    required String userState,
    required String userImage,
    required String userFirstName,
    required String userLastName,
    required String userCellNumber,
    required String userCity,
    required String userAreaCode,
    required String userAddress,
    required String userEmail,
  }) async {
    final document = await user.add({
      userIdColumn: userId,
      userStateColumn: userState,
      userImageColumn: userImage,
      userFirstNameColumn: userFirstName,
      userLastNameColumn: userLastName,
      userCellNumberColumn: userCellNumber,
      userCityColumn: userCity,
      userAreaCodeColumn: userAreaCode,
      userAddressColumn: userAddress,
      userEmailColumn: userEmail,
    });
    final fetchedUser = await document.get();
    return CloudUser(
      documentId: fetchedUser.id,
      userId: userId,
      userState: userState,
      userImage: userImage,
      userFirstName: userFirstName,
      userLastName: userLastName,
      userCellNumber: userCellNumber,
      userCity: userCity,
      userAreaCode: userAreaCode,
      userAddress: userAddress,
      userEmail: userEmail,
    );
  }

// I can add a class to call the server to get the user data using the user id, but I don't think I need to do that



// singleton
  static final FirebaseCloudStorage _shared =
      FirebaseCloudStorage._sharedInstance();
  FirebaseCloudStorage._sharedInstance();
  factory FirebaseCloudStorage() => _shared;
}

So.... is there any way I can efficiently store and retrieve that data?

CodePudding user response:

you can get some properties easily by adding them to the account info, and some of the allowed fields are:

  1. displayName
  2. email
  3. phoneNumber
  4. photoURL

so instead of querying your collection, you can get the current firebase user which will return a datatype of User and the user comes with these properties if you've set them during sign up

e.g

  User? _currentUser = FirebaseAuth.instance.currentUser;

            //for display name
            _currentUser?.displayName;

            //for email
            _currentUser?.email;

            //for phoneNumber
            _currentUser?.phoneNumber;
            
            //for profile picture
            _currentUser?.photoURL;
  • Related