Home > front end >  What is the short hand for checking the result of this function?
What is the short hand for checking the result of this function?

Time:09-13

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;  
    }    
  }

CodePudding user response:

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.

CodePudding user response:

You could write it like this:

String getUID() {
    final String? uid = FirebaseAuth.instance.currentUser?.uid.toString();
  
    return 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.

  • Related