I want to check if the first letter of string is in uppercase in Dart language. How can I implement it? Thanks in advance.
The simplest way I can think of is to compare the first letter of the string with the uppercase equivalent of it. Something like:
bool isUpperCase(String string) {
if (string == null) {
return false;
}
if (string.isEmpty) {
return false;
}
if (string.trimLeft().isEmpty) {
return false;
}
String firstLetter = string.trimLeft().substring(0, 1);
if (double.tryParse(firstLetter) != null) {
return false;
}
return firstLetter.toUpperCase() == string.substring(0, 1);
}
Updated the answer to take in consideration digits.
Also @Saed Nabil is right, this solution will return true if the string starts with any character that is not a letter (except for digits).
You can use the validators
library if you are not already using it.
Then use this method
isUppercase(String str) → bool check if the string str is uppercase
Don't forget to import the dependency, see documentation, to the pubspec.yaml
and to your code import 'package:validators/validators.dart';
.
if(isUppercase(value[0])){
... do some magic
}
You should check that the value
is not empty and not null
first for safety. Like this:
if(value != null && value.isNotEmpty && isUppercase(value[0])){
... do amazing things
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With