Flutter Dart中如何为字符串添加通配符及匹配前缀为Meet的用户角色
1. How to Use Wildcards with Strings in Flutter/Dart?
In Dart, you’ve got a couple of practical ways to handle wildcard-style string matching, depending on how complex your needs are:
Basic substring checks (no regex needed): For simple cases like matching prefixes, suffixes, or any occurrence of a substring, use Dart’s built-in string methods—they’re straightforward and efficient:
startsWith(String pattern): Acts like apattern*wildcard, checking if the string starts with your target patternendsWith(String pattern): Acts like a*patternwildcard, checking if the string ends with your target patterncontains(String pattern): Acts like a*pattern*wildcard, checking if the pattern exists anywhere in the string
Example code:
String sampleRole = "MeetAdmin"; print(sampleRole.startsWith("Meet")); // Returns true print(sampleRole.endsWith("Admin")); // Returns true print(sampleRole.contains("dmi")); // Returns trueRegex for complex wildcards: If you need more flexible patterns (like using
?for single-character matches or*for multi-character matches), convert your wildcard pattern to a regular expression. For example:- Wildcard
Meet?ecbecomes regexMeet.ec(.matches any single character) - Wildcard
*Meet*becomes regex.*Meet.*(matches any string containing "Meet")
Example code:
String role = "MeetPec"; RegExp meetWildcard = RegExp(r'^Meet.*'); // Equivalent to "Meet*" wildcard print(meetWildcard.hasMatch(role)); // Returns true- Wildcard
2. How to Check for Roles Starting with "Meet"?
Your current code checks for an exact match with "Meet", but to catch roles like MeetAdmin or MeetPec, the simplest fix is using the startsWith() method we talked about earlier.
Here’s the modified code:
// Add ?. to safely handle cases where _currentUser["role"] might be null if (_currentUser["role"]?.startsWith("Meet") == true) { // Logic for users with roles starting with "Meet" }
Why this works:
startsWith("Meet")returnstruefor any string that begins exactly with "Meet", no matter what comes after.- The
?.operator prevents null errors: if_currentUser["role"]is null, it returnsnullinstead of crashing, and our comparison totruewill just skip the condition.
If you want to use regex (though it’s overkill for this simple prefix check), you could also write:
RegExp meetPrefixRegex = RegExp(r'^Meet'); // Use ?? "" to pass an empty string if role is null, avoiding regex errors if (meetPrefixRegex.hasMatch(_currentUser["role"] ?? "")) { // Handle the user }
内容的提问来源于stack exchange,提问作者Htet Naing

