dart
Check if a String is empty or null in Dart / Flutter
In this post, we are going to explain how to check if a String is empty or not. We will also cover if the given value is null, false, or 0. If you are using Dart or Flutter to create your application, you can use the code examples listed here.
void checkString(String str) {
if (str.isEmpty) {
print('String is empty');
} else {
print('String is not empty');
}
}
void main() {
checkString('');
// -> String is empty
checkString('hello');
// -> String is not empty
}
Explanation of the above code example
- Created a function checkString that takes the string value as a parameter.
- Inside the checkString() function, we are using String.isEmpty and it will print "String is empty" if the string is empty.
- Testing the above function for two values '' and 'hello'.
Check if values are null, empty, false using List.contains() function
void checkString(value) {
if (['', null, 0, false].contains(value)) {
print('Value is falsey');
} else {
print('Value is OK');
}
}
void main() {
checkString('');
// -> Value is falsey
checkString(null);
// -> Value is falsey
checkString(false);
// -> Value is falsey
checkString('hello');
// -> Value is OK
checkString(0);
// -> Value is falsey
}
Was this helpful?
Similar Posts
- Check if list is empty in Flutter/Dart
- Remove empty and falsey values from a List in Dart/Flutter
- Assign a value to a variable if it is null using Dart
- Remove empty lists from a list of lists and flatten it using Dart
- Assigning a value if it's null
- Reverse a list in Flutter or Dart
- Sort a list in ascending and descending order Dart or Flutter