I couldn't find a way to safely unwrap an optional variable as we do in swift
var myString: String?
if let myString = myString {
print(myString) // myString is a string
}
or in Kotlin
var myString: String?
if (myString != null) {
print(myString) // myString is not null
}
// or
myString?.let {
print(it) // myString is not null
}
In Dart I'm having to do the following, which doesn't look good:
String? myString;
if (myString != null) {
print(myString); // myString still an optional
print(myString!); // myString is now a String! (because of the force unwrap)
}
Is there a way to safely unwrap in a clean way like other null-safety languages? Or we have to always force unwrap variables after a null-check?
Your Dart example seems incomplete but it is difficult to say what is wrong without more context. If myString
is a local variabel it will be promoted. You can see this example:
void main(){
myMethod(null); // NULL VALUE
myMethod('Some text'); // Non-null value: Some text
}
void myMethod(String? string) {
if (string != null) {
printWithoutNull(string);
} else {
print('NULL VALUE');
}
}
// Method which does not allow null as input
void printWithoutNull(String string) => print('Non-null value: $string');
It is a different story if we are talking about class variables. You can see more about that problem here: Dart null safety doesn't work with class fields
A solution to that problem is to copy the class variable into a local variable in your method and then promote the local variable with a null check.
In general, I will recommend reading the articles on the official Dart website about null safety: https://dart.dev/null-safety