You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Dart 3 introduces patterns with guard conditions that can be used with the new switch expression - nice. However, local variable types checked in the guard condition don't get promoted by the compiler even though the dart analyzer doesn't complain.
In the following example, the string s is checked to be not null in the guard condition and the analyzer doesn't complain:
Stringf(int x, {String? s}) =>switch (x) {
_ when s !=null=> s,
_ =>"is null"
};
However compilation fails with:
Error: A value of type 'String?' can't be returned from a function with return type 'String' because 'String?' is nullable and 'String' isn't.
The compile error can be fixed with a non-null assertion _ when s != null => s!,. Now we get an analyzer warning The '!' will have no effect because the receiver can't be null. This warning can then be silenced with // ignore_for_file: unnecessary_non_null_assertion.
The resulting code works. The compiler does correctly promote the type if the same local variable null-check is used in an if condition or ternary expression and we expected the guard condition to behave similarly.
The text was updated successfully, but these errors were encountered:
This is a known issue that I discovered just before 3.0 shipped, when there was no longer time to cherry-pick a fix. The fix has been cherry-picked to stable, and will ship in 3.0.1.
Dart 3 introduces patterns with guard conditions that can be used with the new
switch
expression - nice. However, local variable types checked in the guard condition don't get promoted by the compiler even though thedart analyzer
doesn't complain.In the following example, the string
s
is checked to be not null in the guard condition and the analyzer doesn't complain:However compilation fails with:
The compile error can be fixed with a non-null assertion
_ when s != null => s!,
. Now we get an analyzer warningThe '!' will have no effect because the receiver can't be null
. This warning can then be silenced with// ignore_for_file: unnecessary_non_null_assertion
.The resulting code works. The compiler does correctly promote the type if the same local variable null-check is used in an
if
condition or ternary expression and we expected the guard condition to behave similarly.The text was updated successfully, but these errors were encountered: