To check if a string starts with or ends with a given substring in Dart (and Flutter as well), you can use the startsWith() method and the endsWith() method, respectively:
bool x = myString.startsWith(mySubString);
bool y = myString.endsWith(mySubString);
These methods are case-sensitive (distinguish between uppercase and lowercase letters). If you want they to ignore case-sensitive, you can use regular expressions like so:
bool x = myString.startsWith(RegExp(mySubString, caseSensitive: false));
bool y = myString.endsWith(RegExp(mySubString, caseSensitive: false));
If you don’t clear on what I mean, please see the practical example below.
Example:
// main.dart
import 'package:flutter/foundation.dart';
void main() {
const String s =
'He thrusts his fists against the posts and still insists he sees the ghosts.';
const String s1 = "He thrusts his fists";
const String s2 = "HE THRUSTS HIS FISTS";
const String s3 = "he sees the ghosts.";
const String s4 = "the big ghosts.";
if (kDebugMode) {
print(s.startsWith(s1));
print(s.startsWith(RegExp(s2, caseSensitive: false)));
print(s.endsWith(s3));
print(s.endsWith(s4));
}
}
Output:
true
true
true
false
Further reading:
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- How to Flatten a Nested List in Dart
- How to create a gradient background AppBar in Flutter
- Best Libraries for Making HTTP Requests in Flutter
- Using Stepper widget in Flutter: Tutorial & Example
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.