Hear from Bob and Kevin on the upcoming null-safety feature in Dart.
Sound null safety
Sound null safety is coming to the Dart language! When you opt into null safety, types in your code are non-nullable by default, meaning that values can’t be null unless you say they can be. With null safety, your runtime null-dereference errors turn into edit-time analysis errors.
With null safety, the Dart analyzer enforces good practices. For example, it makes sure you check for null before reading a nullable variable. And because Dart null safety is sound, Dart compilers and runtimes can optimize away internal null checks, so apps can be faster and smaller.
New operators and keywords related to null safety include ?
, !
, and late
. If you’ve used Kotlin, TypeScript, or C#, the syntax for null safety might look familiar. That’s by design: the Dart language aims to be unsurprising.
You can practice using null safety in the web app DartPad with Null Safety, shown in the following screenshot. Or try null safety in your normal development environment, using the instructions and configuration files in the null safety sample.
When creating a variable, you can use ?
and late
to inform Dart of the variable’s nullability.
Here are some examples of declaring non-nullable variables (assuming you’ve opted into null safety):
// In null-safe Dart, none of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();
If the variable can have the value null
, add **?**
to its type declaration:
int? aNullableInt = null;
If you know that a non-nullable variable will be initialized to a non-null value before it’s used, but the Dart analyzer doesn’t agree, insert **late**
before the variable’s type:
class IntProvider {
late int aRealInt;
IntProvider() {
aRealInt = calculate();
}
}
The late
keyword has two effects:
late
variable to a non-null value.late
variable. For example, if a non-nullable instance variable must be calculated, adding the late
modifier delays the calculation until the first use of the instance variable.With null safety, the Dart analyzer generates errors when it finds a nullable value where a non-null value is required. That isn’t as bad as it sounds: the analyzer can often recognize when a variable or expression inside a function has a nullable type but can’t have a null value.
The analyzer can’t model the flow of your whole application, so it can’t predict the values of global variables or class fields.
When using a nullable variable or expression, be sure to handle null values. For example, you can use an if
statement, the ??
operator, or the ?.
operator to handle possible null values.
Here’s an example of using the ??
operator to avoid setting a non-nullable variable to null:
int value = aNullableInt ?? 0; // 0 if it's null; otherwise, the integer
Here’s similar code, but with an if
statement that checks for null:
int definitelyInt(int? aNullableInt) {
if (aNullableInt == null) {
return 0;
}
return aNullableInt; // Can't be null!
}
If you’re sure that an expression with a nullable type isn’t null, you can add !
to make Dart treat it as non-nullable:
int? aNullableInt = 2;
int value = aNullableInt!; // `aNullableInt!` is an int.
// This throws if aNullableInt is null.
Important: If you aren’t positive that a value is non-null, don’t use **!**
.
If you need to change the type of a nullable variable — beyond what the !
operator can do — you can use the typecast operator (as
). The following example uses as
to convert a num?
to an int
:
return maybeNum() as int;
Once you opt into null safety, you can’t use the member access operator ([.](https://dart.dev/guides/language/language-tour#other-operators)
) if the operand might be null. Instead, you can use the null-aware version of that operator (?.
):
double? d;
print(d?.floor()); // Uses `?.` instead of `.` to invoke `floor()`.
Lists, sets, and maps are commonly used collection types in Dart programs, so you need to know how they interact with null safety. Here are some examples of how Dart code uses these collection types:
Column
often have a children
property that’s a List
of Widget
objects.Set
of VeggieCategory
to store a user’s food preferences.fromJson()
method that creates an object from JSON data that’s supplied in a Map<String, dynamic>
.When you’re declaring the type of a list or set, think about what can be null. The following table shows the possibilities for a list of strings if you opt into null safety.
When a literal creates a list or set, then instead of a type like in the table above, you typically see a type annotation on the literal. For example, here’s the code you might use to create a variable (nameList
) of type List<String?>
and a variable (nameSet
) of type Set<String?>
:
var nameList = <String?>['Andrew', 'Anjan', 'Anya'];
var nameSet = <String?>{'Andrew', 'Anjan', 'Anya'};
Map types behave mostly like you’d expect, with one exception: the returned value of a lookup can be null. Null is the value for a key that isn’t present in the map.
As an example, look at the following code. What do you think the value and type of uhOh
are?
var myMap = <String, int>{'one': 1};
var uhOh = myMap['two'];
The answer is that uhOh
is null and has type int?
.
Like lists and sets, maps can have a variety of types:
* Even when all the int values in the map are non-null, when you use an invalid key to do a map lookup, the returned value is null.
Because map lookups can return null, you can’t assign them to non-nullable variables:
// Assigning a lookup result to a non-nullable
// variable causes an error.
int value = <String, int>{'one': 1}['one']; // ERROR
One workaround is to change the type of the variable to be nullable:
int? value = <String, int>{'one': 1}['one']; // OK
Another way to fix the problem — if you’re sure the lookup succeeds — is to add a !
:
int value = <String, int>{'one': 1}['one']!; // OK
A safer approach is to use the lookup value only if it’s not null. You can test its value using an if
statement or the [??](https://dart.dev/guides/language/language-tour#conditional-expressions)
operator. Here’s an example of using the value 0
if the lookup returns a null value:
var aList = <String, int>{'one': 1};
...
int value = aList['one'] ?? 0;
#dart #flutter #mobile-apps