Home > OS >  How can I add Wildcard to the string in flutter dart?
How can I add Wildcard to the string in flutter dart?

Time:10-30

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.

CodePudding user response:

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
}

CodePudding user response:

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

CodePudding user response:

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
}
  • Related