skip to Main Content

I’m learning Dart and I understand that the below (should be) correct. I now want to understand how to do the shorthand version of this. This function lives in my state container (inherited widget) so that I can call this anywhere in my app. Hopefully calling this function everywhere in my app doesn’t count as multiple Firestore queries…

String getUID() {
    final uid = FirebaseAuth.instance.currentUser?.uid.toString();
    if (uid == null || uid == '') {
      return '';
    } else {
      return uid;  
    }    
  }

3

Answers


  1. how about make on helper.dart

    • helper.dart (or whatever you name it)
    import 'the firebase package';
    ...
    String getUID() {
        final uid = FirebaseAuth.instance.currentUser?.uid.toString();
        if (uid == null || uid == '') {
          return '';
        } else {
          return uid;  
        }    
      }
    

    then you can call getUID in every class

    • eg: home.dart
    import 'package:../helper.dart';
    
    ....
    final _uid = getUID();
    print(_uid);
    ....
    

    im not sure this one is best solution, but this what i usually did for common function.

    Login or Signup to reply.
  2. You could write it like this:

    String getUID() {
        final String? uid = FirebaseAuth.instance.currentUser?.uid.toString();
      
        return uid ?? '';
    }
    

    or also as a getter (the getter won’t need parentheses to be accessed (), you just call it as if it were an variable .uid):

    String get uid => FirebaseAuth.instance.currentUser?.uid ?? '';
    

    The ?? operator will work as:

    if(uid == null) {
     return ''; 
    }
    
    return uid;
    

    You don’t need to check for empty string there because you are passing it as empty anyway.

    Login or Signup to reply.
  3. You can write it like so

    String getUID() => FirebaseAuth.instance.currentUser?.uid ?? '';
    

    There is no need for toString() as uid itself is already a String.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search