Sitemap
Dart

Dart is an approachable, portable, and productive language for high-quality apps on any platform. Learn more at https://dart.dev.

Follow publication

Announcing sound null safety

8 min readJun 10, 2020

--

&

Why null safety?

void printLengths(List<File> files) {
for (var file in files) {
print(file.lengthSync());
}
}
void main() {
// Error case 1: passing a null to files.
printLengths(null);
// Error case 2: passing list of files, containing a null item.
printLengths([File('filename1'), File('filename2'), null]);
}

Sound null safety

Design principles

Declaring variables with null safety

// In null-safe Dart, none of these can ever be null.
var i = 42;
final b = Foo();
String m = '';
// These are all nullable variables.
int? j = 1; // Can be null later.
final Foo? c = getFoo(); // Maybe the function returns null.
String? n; // Is null at first. Can be null at any later time, too.
// In function parameters.
void boogie(int? count) {
// It's possible that count is null.
}
// In function return values.
Foo? getFoo() {
// Can return null instead of Foo.
}
// Also: generics, typedefs, type checks, etc.
// And any combination of the above.

Making null safety easier to use

void honk(int? loudness) {
if (loudness == null) {
// No loudness specified, notify the developer
// with maximum loudness.
_playSound('error.wav', volume: 11);
return;
}
// Loudness is non-null, let's just clamp it to acceptable levels.
_playSound('honk.wav', volume: loudness.clamp(0, 11));
}
int sign(int x) {
// The result is non-nullable.
int result;
if (x >= 0) {
result = 1;
} else {
result = -1;
}
// By this point, Dart knows the result cannot be null.
return result;
}
class Goo {
late Viscosity v;
Goo(Material m) {
v = m.computeViscosity();
}
}

Null safety is backwards compatible

The null safety roadmap

Try it now

--

--

Dart
Dart

Published in Dart

Dart is an approachable, portable, and productive language for high-quality apps on any platform. Learn more at https://dart.dev.

Filip Hracek
Filip Hracek

Written by Filip Hracek

I’m a pro­gram­ming buff with formal train­ing in jour­nal­ism. I build games, teach pro­gram­ming, explain things, and create silly soft­ware experiments.

Responses (16)