11

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?

Vitor
  • 762
  • 6
  • 26
  • Are you sure about the Dart example you have made? How did you determine that Dart are still seeing `myString` as nullable after your `if`? – julemand101 Mar 11 '21 at 13:57
  • @julemand101 I mean, the analyzer still considering it as an optional string even though we know it is not. – Vitor Mar 11 '21 at 14:08

2 Answers2

6

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

julemand101
  • 28,470
  • 5
  • 52
  • 48
0
void main(List<String> args) {
  var x;
  if (x != null) {
    // Since you've already checked, the following statement won't give an error.
    print(x!);
  } else {
    print('ERROR');
  }
}

I guess this is how you can safely unwrap optionals or variables that can either be null in Dart.

Dharman
  • 30,962
  • 25
  • 85
  • 135
havoc_785
  • 17
  • 1
  • 1