Home > Enterprise >  How do I get the current Firebase UID and write it to Realtime Database?
How do I get the current Firebase UID and write it to Realtime Database?

Time:12-15

I followed a tutorial to create this AuthService class. This is working well.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:app/models/user.dart' as UserModel;

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // create CurrentUser object based on Firebase user object
  UserModel.User? _userFromFirebaseUser(User? user) {
    // return user != null ? UserModel.User(uid: user.uid) : null;
    if (user != null) {
      return UserModel.User(uid: user.uid);
    } else {
      return null;
    }
  }

  //auth change user stream
  Stream<UserModel.User?> get user {
    return _auth.authStateChanges()
        // .map((User? user) => _userFromFirebaseUser(user));
      .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 pass
  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;
      return _userFromFirebaseUser(user);
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

  //sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

}

However, I now want to use the current Firebase UID to write it to Realtime Database whenever the user sends a chat on the chat screen. How would I do this? I attempted this below but got lost (see the OnPressed event of the FloatingActionButton).

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:app/services/auth.dart';
import 'package:app/models/user.dart';

class Chat extends StatelessWidget { 
  Chat({Key? key}) : super(key: key);
  final database = FirebaseDatabase.instance.reference();

  @override
  Widget build(BuildContext context) {
    final groupChatRef = database.child('GroupID');

    return Scaffold(
      appBar: AppBar(
        title: Text('Group Chat Screen'),
        // actions: [
        //   TextButton.icon(
        //       onPressed: {
        //         Navigator.pop(context);
        //       },
        //       icon: icon,
        //       label: label
        //   )
        // ],
      ),
      body: Align(
        alignment: Alignment.bottomLeft,
        child: Row(
          children: [
            Expanded(
              child: TextField(
                  decoration: InputDecoration(
                    hintText: "Write message...",
                  )
              ),
            ),
            FloatingActionButton(
              onPressed: () {
                var uid;
                final user = User(uid: uid);
                final myAuth = AuthService();
                print('MyAuth.user:');
                //This is where I get lost...
              },
              child: Icon(Icons.send,color: Colors.white,size: 18,),
              backgroundColor: Colors.blue,
              elevation: 0,
            )
          ],
        ),
      )
    );
  }
}

CodePudding user response:

You can get the user uid by adding a getter in auth service

class AuthService {
  ...
  User? get currentUser => _auth.currentUser;
  ...

Then in your floating action button get this user and use it's uid

Also, it would be much better to use dependency injection and stop creating instances every time you need them.

              onPressed: () {
                final String uid = authService.currentUser!.uid;
                // do other things
              },
  • Related