1

The following code will give the current user whose role is Meet.

_currentUser["role"] == "Meet"

But in reality, I'd like to get the current user whose role is prefixed with Meet. eg.MeetAdmin, MeetPec, like that. Please help me how do I do that.

3 Answers 3

2

You can create an extension on String:

extension StringExtension on String {
  bool hasPrefix(String prefix) {
    return substring(0, prefix.length) == prefix;
  }
}


void main() {
  final role = 'MeetPec';
  final invalidRole = 'PecMeet';
  
  print(role.hasPrefix('Meet')); // returns true
  print(invalidRole.hasPrefix('Meet')); // returns false
}

It assumes case-sensitive check, but you can tweak it to also support case-insensitive by adding .toLowerCase() to both prefix and the string itself.

EDIT: As pointed out in the comments, we already have a startsWith method, this is definitely a way to go here:

void main() {
  final role = 'MeetPec';
  final invalidRole = 'PecMeet';
  
  print(role.startsWith('Meet')); // returns true
  print(invalidRole.startsWith('Meet')); // returns false
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why don't just use the startsWith method?
@enzo of course, I just blindly added an answer based on the previous approaches without digging into what we are provided with already. For sure, using startsWith is the way to go.
Thank you so much. You have precisely helped me. This is the best answer I've ever got.
0

Okay, if I understand your question property, you want to check if the current user role has the word "meet" in it.

If that's the case your can use contains to check if the role contains role

Example

if(_currentUser["role"].contains("meet") ) {
  //It contains meet
}else{
 //It does not contain meet
}

1 Comment

Thank you so much for your answer. This is the first time hearing the contains method.
0

check this method it might help you. whenever you want to check or search you should convert string to lower case to compare then check

        bool getCurrentUserWithMeet() {
      Map<String, String> _currentUser = {
        'role': 'MeetAdmin',
      };

      final isCurrentUserContainsMeet =
          _currentUser['role']?.toLowerCase().contains('meet');
          
      return isCurrentUserContainsMeet ?? false;
    }

1 Comment

Thank you so much. This is my first time of seeing such kind of approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.