Cara menggunakan php parameter default null

Null safety is the largest change we’ve made to Dart since we replaced the original unsound optional type system with a sound static type system in Dart 2.0. When Dart first launched, compile-time null safety was a rare feature needing a long introduction. Today, Kotlin, Swift, Rust, and other languages all have their own answers to what has become a very familiar problem. Here is an example:

// Without null safety:
bool isEmpty(String string) => string.length == 0;

main() {
  isEmpty(null);
}

If you run this Dart program without null safety, it throws a

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
4 exception on the call to
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
5. The
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 value is an instance of the
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 class, and
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 has no “length” getter. Runtime failures suck. This is especially true in a language like Dart that is designed to run on an end-user’s device. If a server application fails, you can often restart it before anyone notices. But when a Flutter app crashes on a user’s phone, they are not happy. When your users aren’t happy, you aren’t happy.

Developers like statically-typed languages like Dart because they enable the type checker to find mistakes in code at compile time, usually right in the IDE. The sooner you find a bug, the sooner you can fix it. When language designers talk about “fixing null reference errors”, they mean enriching the static type checker so that the language can detect mistakes like the above attempt to call

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
5 on a value that might be
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6.

There is no one true solution to this problem. Rust and Kotlin both have their own approach that makes sense in the context of those languages. This doc walks through all the details of our answer for Dart. It includes changes to the static type system and a suite of other modifications and new language features to let you not only write null-safe code but hopefully to enjoy doing so.

This document is long. If you want something shorter that covers just what you need to know to get up and running, start with the overview. When you are ready for a deeper understanding and have the time, come back here so you can understand how the language handles

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, why we designed it that way, and how to write idiomatic, modern, null-safe Dart. (Spoiler alert: it ends up surprisingly close to how you write Dart today.)

The various ways a language can tackle null reference errors each have their pros and cons. These principles guided the choices we made:

  • Code should be safe by default. If you write new Dart code and don’t use any explicitly unsafe features, it never throws a null reference error at runtime. All possible null reference errors are caught statically. If you want to defer some of that checking to runtime to get greater flexibility, you can, but you have to choose that by using some feature that is textually visible in the code.

    In other words, we aren’t giving you a life jacket and leaving it up to you to remember to put it on every time you go out on the water. Instead, we give you a boat that doesn’t sink. You stay dry unless you jump overboard.

  • Null safe code should be easy to write. Most existing Dart code is dynamically correct and does not throw null reference errors. You like your Dart program the way it looks now, and we want you to be able to keep writing code that way. Safety shouldn’t require sacrificing usability, paying penance to the type checker, or having to significantly change the way you think.

  • The resulting null safe code should be fully sound. “Soundness” in the context of static checking means different things to different people. For us, in the context of null safety, that means that if an expression has a static type that does not permit

    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6, then no possible execution of that expression can ever evaluate to
    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6. The language provides this guarantee mostly through static checks, but there can be some runtime checks involved too. (Though, note the first principle: any place where those runtime checks happen will be your choice.)

    Soundness is important for user confidence. A boat that mostly stays afloat is not one you’re enthused to brave the open seas on. But it’s also important for our intrepid compiler hackers. When the language makes hard guarantees about semantic properties of a program, it means that the compiler can perform optimizations that assume those properties are true. When it comes to

    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6, it means we can generate smaller code that eliminates unneeded
    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6 checks, and faster code that doesn’t need to verify a receiver is non-
    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6 before calling methods on it.

    One caveat: We only guarantee soundness in Dart programs that are fully null safe. Dart supports programs that contain a mixture of newer null safe code and older legacy code. In these mixed-version programs, null reference errors may still occur. In a mixed-version program, you get all of the static safety benefits in the portions that are null safe, but you don’t get full runtime soundness until the entire application is null safe.

Note that eliminating

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 is not a goal. There’s nothing wrong with
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. On the contrary, it’s really useful to be able to represent the absence of a value. Building support for a special “absent” value directly into the language makes working with absence flexible and usable. It underpins optional parameters, the handy
// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 null-aware operator, and default initialization. It is not
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 that is bad, it is having
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 go where you don’t expect it that causes problems.

Thus with null safety, our goal is to give you control and insight into where

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 can flow through your program and certainty that it can’t flow somewhere that would cause a crash.

Nullability in the type system

Null safety begins in the static type system because everything else rests upon that. Your Dart program has a whole universe of types in it: primitive types like

// Without null safety:
String missingReturn() {
  // No return.
}
3 and
// Without null safety:
String missingReturn() {
  // No return.
}
4, collection types like
// Without null safety:
String missingReturn() {
  // No return.
}
5, and all of the classes and types you and the packages you use define. Before null safety, the static type system allowed the value
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 to flow into expressions of any of those types.

In type theory lingo, the

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 type was treated as a subtype of all types:

Cara menggunakan php parameter default null

The set of operations—getters, setters, methods, and operators—allowed on some expressions are defined by its type. If the type is

// Without null safety:
String missingReturn() {
  // No return.
}
5, you can call
// Without null safety:
String missingReturn() {
  // No return.
}
9 or
// Using null safety:
String alwaysReturns(int n) {
  if (n == 0) {
    return 'zero';
  } else if (n < 0) {
    throw ArgumentError('Negative values not allowed.');
  } else {
    if (n > 1000) {
      return 'big';
    } else {
      return n.toString();
    }
  }
}
0 on it. If it’s
// Without null safety:
String missingReturn() {
  // No return.
}
3, you can call
// Using null safety:
String alwaysReturns(int n) {
  if (n == 0) {
    return 'zero';
  } else if (n < 0) {
    throw ArgumentError('Negative values not allowed.');
  } else {
    if (n > 1000) {
      return 'big';
    } else {
      return n.toString();
    }
  }
}
2. But the
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 value doesn’t define any of those methods. Allowing
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 to flow into an expression of some other type means any of those operations can fail. This is really the crux of null reference errors—every failure comes from trying to look up a method or property on
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 that it doesn’t have.

Non-nullable and nullable types

Null safety eliminates that problem at the root by changing the type hierarchy. The

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 type still exists, but it’s no longer a subtype of all types. Instead, the type hierarchy looks like this:

Cara menggunakan php parameter default null

Since

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 is no longer a subtype, no type except the special
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 class permits the value
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. We’ve made all types non-nullable by default. If you have a variable of type
// Without null safety:
String missingReturn() {
  // No return.
}
4, it will always contain a string. There, we’ve fixed all null reference errors.

If we didn’t think

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 was useful at all, we could stop here. But
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 is useful, so we still need a way to handle it. Optional parameters are a good illustrative case. Consider this null safe Dart code:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}

Here, we want to allow the

// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
3 parameter to accept any string, or the value
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, but nothing else. To express that, we give
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
3 a nullable type by slapping
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
6 at the end of the underlying base type
// Without null safety:
String missingReturn() {
  // No return.
}
4. Under the hood, this is essentially defining a union of the underlying type and the
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 type. So
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
9 would be a shorthand for
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
00 if Dart had full-featured union types.

Using nullable types

If you have an expression with a nullable type, what can you do with the result? Since our principle is safe by default, the answer is not much. We can’t let you call methods of the underlying type on it because those might fail if the value is

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}

This would crash if we let you run it. The only methods and properties we can safely let you access are ones defined by both the underlying type and the

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 class. That’s just
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
03,
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
04, and
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
05. So you can use nullable types as map keys, store them in sets, compare them to other values, and use them in string interpolation, but that’s about it.

How do they interact with non-nullable types? It’s always safe to pass a non-nullable type to something expecting a nullable type. If a function accepts

// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
9 then passing a
// Without null safety:
String missingReturn() {
  // No return.
}
4 is allowed because it won’t cause any problems. We model this by making every nullable type a supertype of its underlying type. You can also safely pass
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 to something expecting a nullable type, so
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 is also a subtype of every nullable type:

Cara menggunakan php parameter default null

But going the other direction and passing a nullable type to something expecting the underlying non-nullable type is unsafe. Code that expects a

// Without null safety:
String missingReturn() {
  // No return.
}
4 may call
// Without null safety:
String missingReturn() {
  // No return.
}
4 methods on the value. If you pass a
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
9 to it,
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 could flow in and that could fail:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}

This program is not safe and we shouldn’t allow it. However, Dart has always had this thing called implicit downcasts. If you, for example, pass a value of type

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14 to a function expecting an
// Without null safety:
String missingReturn() {
  // No return.
}
4, the type checker allows it:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}

To maintain soundness, the compiler silently inserts an

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
16 cast on the argument to
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
17. That cast could fail and throw an exception at runtime, but at compile time, Dart says this is OK. Since non-nullable types are modeled as subtypes of nullable types, implicit downcasts would let you pass a
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
9 to something expecting a
// Without null safety:
String missingReturn() {
  // No return.
}
4. Allowing that would violate our goal of being safe by default. So with null safety we are removing implicit downcasts entirely.

This makes the call to

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
20 produce a compile error, which is what you want. But it also means all implicit downcasts become compile errors, including the call to
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
17. You’ll have to add the explicit downcast yourself:

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}

We think this is an overall good change. Our impression is that most users never liked implicit downcasts. In particular, you may have been burned by this before:

// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}

Spot the bug? The

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
22 method is lazy, so it returns an
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
23, not a
// Without null safety:
String missingReturn() {
  // No return.
}
5. This program compiles but then throws an exception at runtime when it tries to cast that
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
23 to the
// Without null safety:
String missingReturn() {
  // No return.
}
5 type that
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
27 declares it returns. With the removal of implicit downcasts, this becomes a compile error.

Where were we? Right, OK, so it’s as if we’ve taken the universe of types in your program and split them into two halves:

Cara menggunakan php parameter default null

There is a region of non-nullable types. Those types let you access all of the interesting methods, but can never ever contain

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. And then there is a parallel family of all of the corresponding nullable types. Those permit
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, but you can’t do much with them. We let values flow from the non-nullable side to the nullable side because doing so is safe, but not the other direction.

That seems like nullable types are basically useless. They have no methods and you can’t get away from them. Don’t worry, we have a whole suite of features to help you move values from the nullable half over to the other side that we will get to soon.

Top and bottom

This section is a little esoteric. You can mostly skip it, except for two bullets at the very end, unless you’re into type system stuff. Imagine all the types in your program with edges between ones that are subtypes and supertypes of each other. If you were to draw it, like the diagrams in this doc, it would form a huge directed graph with supertypes like

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14 near the top and leaf classes like your own types near the bottom.

If that directed graph comes to a point at the top where there is a single type that is the supertype (directly or indirectly), that type is called the top type. Likewise, if there is a weird type at that bottom that is a subtype of every type, you have a bottom type. (In this case, your directed graph is a lattice.)

It’s convenient if your type system has a top and bottom type, because it means that type-level operations like least upper bound (which type inference uses to figure out the type of a conditional expression based on the types of its two branches) can always produce a type. Before null safety,

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14 was Dart’s top type and
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 was its bottom type.

Since

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14 is non-nullable now, it is no longer a top type.
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 is not a subtype of it. Dart has no named top type. If you need a top type, you want
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
35. Likewise,
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 is no longer the bottom type. If it was, everything would still be nullable. Instead, we’ve added a new bottom type named
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37:

Cara menggunakan php parameter default null

In practice, this means:

  • If you want to indicate that you allow a value of any type, use

    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    35 instead of
    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    14. In fact, it becomes pretty unusual to use
    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    14 since that type means “could be any possible value except this one weirdly prohibited value
    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6”.

  • On the rare occasion that you need a bottom type, use

    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    37 instead of
    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    7. If you don’t know if you need a bottom type, you probably don’t.

Ensuring correctness

We divided the universe of types into nullable and non-nullable halves. In order to maintain soundness and our principle that you can never get a null reference error at runtime unless you ask for it, we need to guarantee that

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 never appears in any type on the non-nullable side.

Getting rid of implicit downcasts and removing

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
7 as a bottom type covers all of the main places that types flow through a program across assignments and from arguments into parameters on function calls. The main remaining places where
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 can sneak in are when a variable first comes into being and when you leave a function. So there are some additional compile errors:

Invalid returns

If a function has a non-nullable return type, then every path through the function must reach a

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
47 statement that returns a value. Before null safety, Dart was pretty lax about missing returns. For example:

// Without null safety:
String missingReturn() {
  // No return.
}

If you analyzed this, you got a gentle hint that maybe you forgot a return, but if not, no big deal. That’s because if execution reaches the end of a function body then Dart implicitly returns

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. Since every type is nullable, technically this function is safe, even though it’s probably not what you want.

With sound non-nullable types, this program is flat out wrong and unsafe. Under null safety, you get a compile error if a function with a non-nullable return type doesn’t reliably return a value. By “reliably”, I mean that the language analyzes all of the control flow paths through the function. As long as they all return something, it is satisfied. The analysis is pretty smart, so even this function is OK:

// Using null safety:
String alwaysReturns(int n) {
  if (n == 0) {
    return 'zero';
  } else if (n < 0) {
    throw ArgumentError('Negative values not allowed.');
  } else {
    if (n > 1000) {
      return 'big';
    } else {
      return n.toString();
    }
  }
}

We’ll dive more deeply into the new flow analysis in the next section.

Uninitialized variables

When you declare a variable, if you don’t give it an explicit initializer, Dart default initializes the variable with

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. That’s convenient, but obviously totally unsafe if the variable’s type is non-nullable. So we have to tighten things up for non-nullable variables:

  • Top level variable and static field declarations must have an initializer. Since these can be accessed and assigned from anywhere in the program, it’s impossible for the compiler to guarantee that the variable has been given a value before it gets used. The only safe option is to require the declaration itself to have an initializing expression that produces a value of the right type:

    // Using null safety:
    int topLevel = 0;
    
    class SomeClass {
      static int staticField = 0;
    }
    

  • Instance fields must either have an initializer at the declaration, use an initializing formal, or be initialized in the constructor’s initialization list. That’s a lot of jargon. Here are the examples:

    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    0

    In other words, as long as the field has a value before you reach the constructor body, you’re good.

  • Local variables are the most flexible case. A non-nullable local variable doesn’t need to have an initializer. This is perfectly fine:

    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    1

    The rule is only that a local variable must be definitely assigned before it is used. We get to rely on the new flow analysis I alluded to for this as well. As long as every path to a variable’s use initializes it first, the use is OK.

  • Optional parameters must have a default value. If you don’t pass an argument for an optional positional or named parameter, then the language fills it in with the default value. If you don’t specify a default value, the default default value is

    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6, and that doesn’t fly if the parameter’s type is non-nullable.

    So, if you want a parameter to be optional, you need to either make it nullable or specify a valid non-

    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6 default value.

These restrictions sound onerous, but they aren’t too bad in practice. They are very similar to the existing restrictions around

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
52 variables and you’ve likely been working with those for years without even really noticing. Also, remember that these only apply to non-nullable variables. You can always make the type nullable and then get the default initialization to
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6.

Even so, the rules do cause friction. Fortunately, we have a suite of new language features to lubricate the most common patterns where these new limitations slow you down. First, though, it’s time to talk about flow analysis.

Flow analysis

Control flow analysis has been around in compilers for years. It’s mostly hidden from users and used during compiler optimization, but some newer languages have started to use the same techniques for visible language features. Dart already has a dash of flow analysis in the form of type promotion:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
2

Note how on the marked line, we can call

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
54 on
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55. That method is defined on
// Without null safety:
String missingReturn() {
  // No return.
}
5, not
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14. This works because the type checker looks at all of the
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
58 expressions and the control flow paths in the program. If the body of some control flow construct only executes when a certain
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
58 expression on a variable is true, then inside that body the variable’s type is “promoted” to the tested type.

In the example here, the then branch of the

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
60 statement only runs when
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55 actually contains a list. Therefore, Dart promotes
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55 to type
// Without null safety:
String missingReturn() {
  // No return.
}
5 instead of its declared type
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14. This is a handy feature, but it’s pretty limited. Prior to null safety, the following functionally identical program did not work:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
3

Again, you can only reach the

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
65 call when
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55 contains a list, so this program is dynamically correct. But the type promotion rules were not smart enough to see that the
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
47 statement means the second statement can only be reached when
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55 is a list.

For null safety, we’ve taken this limited analysis and made it much more powerful in several ways.

Reachability analysis

First off, we fixed the long-standing complaint that type promotion isn’t smart about early returns and other unreachable code paths. When analyzing a function, it now takes into account

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
47,
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
70,
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
71, and any other way execution might terminate early in a function. Under null safety, this function:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
4

Is now perfectly valid. Since the

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
60 statement will exit the function when
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55 is not a
// Without null safety:
String missingReturn() {
  // No return.
}
5, Dart promotes
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55 to be
// Without null safety:
String missingReturn() {
  // No return.
}
5 on the second statement. This is a really nice improvement that helps a lot of Dart code, even stuff not related to nullability.

Never for unreachable code

You can also program this reachability analysis. The new bottom type

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37 has no values. (What kind of value is simultaneously a
// Without null safety:
String missingReturn() {
  // No return.
}
4,
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
79, and
// Without null safety:
String missingReturn() {
  // No return.
}
3?) So what does it mean for an expression to have type
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37? It means that expression can never successfully finish evaluating. It must throw an exception, abort, or otherwise ensure that the surrounding code expecting the result of the expression never runs.

In fact, according to the language, the static type of a

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
71 expression is
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37. The type
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37 is declared in the core libraries and you can use it as a type annotation. Maybe you have a helper function to make it easier to throw a certain kind of exception:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
5

You might use it like so:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
6

This program analyzes without error. Notice that the last line of the

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
04 method accesses
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
86 and
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
87 on
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
88. It has been promoted to
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
89 even though the function doesn’t have any
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
47 or
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
71. The control flow analysis knows that the declared type of
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
92 is
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37 which means the then branch of the
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
60 statement must abort somehow. Since the second statement can only be reached when
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
88 is a
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
89, Dart promotes it.

In other words, using

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
37 in your own APIs lets you extend Dart’s reachability analysis.

Definite assignment analysis

I mentioned this one briefly with local variables. Dart needs to ensure a non-nullable local variable is always initialized before it is read. We use definite assignment analysis to be as flexible about that as possible. The language analyzes each function body and tracks the assignments to local variables and parameters through all control flow paths. As long as the variable is assigned on every path that reaches some use of a variable, the variable is considered initialized. This lets you declare a variable with no initializer and then initialize it afterwards using complex control flow, even when the variable has a non-nullable type.

We also use definite assignment analysis to make final variables more flexible. Before null safety, it can be difficult to use

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
52 for local variables if you need to initialize them in any sort of interesting way:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
7

This would be an error since the

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
99 variable is
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
52 but has no initializer. With the smarter flow analysis under null safety, this program is fine. The analysis can tell that
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
99 is definitely initialized exactly once on every control flow path, so the constraints for marking a variable
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
52 are satisfied.

Type promotion on null checks

The smarter flow analysis helps lots of Dart code, even code not related to nullability. But it’s not a coincidence that we’re making these changes now. We have partitioned types into nullable and non-nullable sets. If you have a value of a nullable type, you can’t really do anything useful with it. In cases where the value is

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, that restriction is good. It’s preventing you from crashing.

But if the value isn’t

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, it would be good to be able to move it over to the non-nullable side so you can call methods on it. Flow analysis is one of the primary ways to do this for local variables and parameters. We’ve extended type promotion to also look at
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
05 and
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
06 expressions.

If you check a local variable with nullable type to see if it is not

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, Dart then promotes the variable to the underlying non-nullable type:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
8

Here,

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
08 has a nullable type. Normally, that prohibits you from calling
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
09 on it. But because we have guarded that call in an
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
60 statement that checks to ensure the value is not
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, Dart promotes it from
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
12 to
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
13 and lets you call methods on it or pass it to functions that expect non-nullable lists.

This sounds like a fairly minor thing, but this flow-based promotion on null checks is what makes most existing Dart code work under null safety. Most Dart code is dynamically correct and does avoid throwing null reference errors by checking for

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 before calling methods. The new flow analysis on null checks turns that dynamic correctness into provable static correctness.

It also, of course, works with the smarter analysis we do for reachability. The above function can be written just as well as:

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
9

The language is also smarter about what kinds of expressions cause promotion. An explicit

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
05 or
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
06 of course works. But explicit casts using
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
17, or assignments, or the postfix
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 operator we’ll get to soon also cause promotion. The general goal is that if the code is dynamically correct and it’s reasonable to figure that out statically, the analysis should be clever enough to do so.

Note that type promotion only works on local variables, not on fields or top-level variables. For more information about working with non-local variables, see .

Unnecessary code warnings

Having smarter reachability analysis and knowing where

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 can flow through your program helps ensure that you add code to handle
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. But we can also use that same analysis to detect code that you don’t need. Before null safety, if you wrote something like:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
0

Dart had no way of knowing if that null-aware

// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 operator is useful or not. For all it knows, you could pass
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 to the function. But in null safe Dart, if you have annotated that function with the now non-nullable
// Without null safety:
String missingReturn() {
  // No return.
}
5 type, then it knows
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
24 will never be
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. That implies the
// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 will never do anything useful and you can and should just use
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
27.

To help you simplify your code, we’ve added warnings for unnecessary code like this now that the static analysis is precise enough to detect it. Using a null-aware operator or even a check like

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
05 or
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
06 on a non-nullable type gets reported as a warning.

And, of course, this plays with non-nullable type promotion too. Once a variable has been promoted to a non-nullable type, you get a warning if you redundantly check it again for

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
1

You get a warning on the

// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 here because at the point that it executes, we already know
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
24 cannot be
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. The goal with these warnings is not just to clean up pointless code. By removing unneeded checks for
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, we ensure that the remaining meaningful checks stand out. We want you to be able to look at your code and see where
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 can flow.

Working with nullable types

We’ve now corralled

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 into the set of nullable types. With flow analysis, we can safely let some non-
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 values hop over the fence to the non-nullable side where we can use them. That’s a big step, but if we stop here, the resulting system is still painfully restrictive. Flow analysis only helps with locals and parameters.

To try to regain as much of the flexibility that Dart had before null safety—and to go beyond it on some places—we have a handful of other new features.

Smarter null-aware methods

Dart’s null aware operator

// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 is much older than null safety. The runtime semantics state that if the receiver is
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 then the property access on the right-hand side is skipped and the expression evaluates to
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
2

Instead of throwing an exception, this prints “null”. The null-aware operator is a nice tool for making nullable types usable in Dart. While we can’t let you call methods on nullable types, we can and do let you use null-aware operators on them. The post-null safety version of the program is:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
3

It works just like the previous one.

However, if you’ve ever used null-aware operators in Dart, you’ve probably encountered an annoyance when using them in method chains. Let’s say you want to see if the length of a potentially absent string is an even number (not a particularly realistic problem, I know, but work with me here):

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
4

Even though this program uses

// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9, it still throws an exception at runtime. The problem is that the receiver of the
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
42 expression is the result of the entire
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
43 expression to its left. That expression evaluates to
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, so we get a null reference error trying to call
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
42. If you’ve ever used
// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 in Dart, you probably learned the hard way that you have to apply the null-aware operator to every property or method in a chain after you use it once:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
5

This is annoying, but, worse, it obscures important information. Consider:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
6

Here’s a question for you: Can the

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
47 getter on
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
48 return
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6? It looks like it could because you’re using
// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 on the result. But it may just be that the second
// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 is only there to handle cases where
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
52 is
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, not the result of
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
47. You can’t tell.

To address this, we borrowed a smart idea from C#’s design of the same feature. When you use a null-aware operator in a method chain, if the receiver evaluates to

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, then the entire rest of the method chain is short-circuited and skipped. This means if
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
47 has a non-nullable return type, then you can and should write:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
7

In fact, you’ll get an unnecessary code warning on the second

// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 if you don’t. If you see code like:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
6

Then you know for certain it means that

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
47 itself has a nullable return type. Each
// Without null safety:
List<int> filterEvens(List<int> ints) {
  return ints.where((n) => n.isEven);
}
9 corresponds to a unique path that can cause
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 to flow into the method chain. This makes null-aware operators in method chains both more terse and more precise.

While we were at it, we added a couple of other null-aware operators:

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
9

There isn’t a null-aware function call operator, but you can write:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
0

Null assertion operator

The great thing about using flow analysis to move a nullable variable to the non-nullable side of the world is that doing so is provably safe. You get to call methods on the previously-nullable variable without giving up any of the safety or performance of non-nullable types.

But many valid uses of nullable types can’t be proven to be safe in a way that pleases static analysis. For example:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
1

If you try to run this, you get a compile error on the call to

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
61. The
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
62 field is nullable because it won’t have a value in a successful response. We can see by inspecting the class that we never access the
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
62 message when it is
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. But that requires understanding the relationship between the value of
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
65 and the nullability of
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
62. The type checker can’t see that connection.

In other words, we human maintainers of the code know that error won’t be

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 at the point that we use it and we need a way to assert that. Normally, you assert types using an
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
17 cast, and you can do the same thing here:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
2

Casting

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
62 to the non-nullable
// Without null safety:
String missingReturn() {
  // No return.
}
4 type will throw a runtime exception if the cast fails. Otherwise, it gives us a non-nullable string that we can then call methods on.

“Casting away nullability” comes up often enough that we have a new shorthand syntax. A postfix exclamation mark (

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18) takes the expression on the left and casts it to its underlying non-nullable type. So the above function is equivalent to:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
3

This one-character “bang operator” is particularly handy when the underlying type is verbose. It would be really annoying to have to write

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
72 just to cast away a single
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
6 from some type.

Of course, like any cast, using

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 comes with a loss of static safety. The cast must be checked at runtime to preserve soundness and it may fail and throw an exception. But you have control over where these casts are inserted, and you can always see them by looking through your code.

Late variables

The most common place where the type checker cannot prove the safety of code is around top-level variables and fields. Here is an example:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
4

Here, the

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
75 method is called before
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
76. That means
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
77 will be initialized to a non-null value before it is used. But it’s not feasible for a static analysis to determine that. (It might be possible for a trivial example like this one, but the general case of trying to track the state of each instance of a class is intractable.)

Because the type checker can’t analyze uses of fields and top-level variables, it has a conservative rule that non-nullable fields have to be initialized either at their declaration (or in the constructor initialization list for instance fields). So Dart reports a compile error on this class.

You can fix the error by making the field nullable and then using null assertion operators on the uses:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
5

This works fine. But it sends a confusing signal to the maintainer of the class. By marking

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
77 nullable, you imply that
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 is a useful, meaningful value for that field. But that’s not the intent. The
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
77 field should never be observed in its
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 state.

To handle the common pattern of state with delayed initialization, we’ve added a new modifier,

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82. You can use it like this:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
6

Note that the

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
77 field has a non-nullable type, but is not initialized. Also, there’s no explicit null assertion when it’s used. There are a few models you can apply to the semantics of
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82, but I think of it like this: The
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 modifier means “enforce this variable’s constraints at runtime instead of at compile time”. It’s almost like the word “late” describes when it enforces the variable’s guarantees.

In this case, since the field is not definitely initialized, every time the field is read, a runtime check is inserted to make sure it has been assigned a value. If it hasn’t, an exception is thrown. Giving the variable the type

// Without null safety:
String missingReturn() {
  // No return.
}
4 means “you should never see me with a value other than a string” and the
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 modifier means “verify that at runtime”.

In some ways, the

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 modifier is more “magical” than using
// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
6 because any use of the field could fail, and there isn’t anything textually visible at the use site. But you do have to write
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 at the declaration to get this behavior, and our belief is that seeing the modifier there is explicit enough for this to be maintainable.

In return, you get better static safety than using a nullable type. Because the field’s type is non-nullable now, it is a compile error to try to assign

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 or a nullable
// Without null safety:
String missingReturn() {
  // No return.
}
4 to the field. The
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 modifier lets you defer initialization, but still prohibits you from treating it like a nullable variable.

Lazy initialization

The

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 modifier has some other special powers too. It may seem paradoxical, but you can use
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 on a field that has an initializer:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
7

When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed. In other words, it works exactly like an initializer on a top-level variable or static field. This can be handy when the initialization expression is costly and may not be needed.

Running the initializer lazily gives you an extra bonus when you use

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 on an instance field. Usually instance field initializers cannot access
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
97 because you don’t have access to the new object until all field initializers have completed. But with a
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 field, that’s no longer true, so you can access
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
97, call methods, or access fields on the instance.

Late final variables

You can also combine

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 with
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
52:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
8

Unlike normal

// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
52 fields, you do not have to initialize the field in its declaration or in the constructor initialization list. You can assign to it later at runtime. But you can only assign to it once, and that fact is checked at runtime. If you try to assign to it more than once—like calling both
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
75 and
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
04 here—the second assignment throws an exception. This is a great way to model state that gets initialized eventually and is immutable afterwards.

In other words, the new

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 modifier in combination with Dart’s other variable modifiers covers most of the feature space of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
06 in Kotlin and
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
07 in Swift. You can even use it on local variables if you want a little local lazy evaluation.

Required named parameters

To guarantee that you never see a

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 parameter with a non-nullable type, the type checker requires all optional parameters to either have a nullable type or a default value. What if you want to have a named parameter with a non-nullable type and no default value? That would imply that you want to require the caller to always pass it. In other words, you want a parameter that is named but not optional.

I visualize the various kinds of Dart parameters with this table:

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
9

For unclear reasons, Dart has long supported three corners of this table but left the combination of named+mandatory empty. With null safety, we filled that in. You declare a required named parameter by placing

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
09 before the parameter:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
0

Here, all the parameters must be passed by name. The parameters

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
10 and
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
11 are optional and can be omitted. The parameters
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
12 and
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
13 are required and must be passed. Note that required-ness is independent of nullability. You can have required named parameters of nullable types, and optional named parameters of non-nullable types (if they have a default value).

This is another one of those features that I think makes Dart better regardless of null safety. It simply makes the language feel more complete to me.

Abstract fields

One of the neat features of Dart is that it upholds a thing called the uniform access principle. In human terms it means that fields are indistinguishable from getters and setters. It’s an implementation detail whether a “property” in some Dart class is computed or stored. Because of this, when defining an interface using an abstract class, it’s typical to use a field declaration:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
1

The intent is that users only implement that class and don’t extend it. The field syntax is simply a shorter way of writing a getter/setter pair:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
2

But Dart doesn’t know that this class will never be used as a concrete type. It sees that

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
14 declaration as a real field. And, unfortunately, that field is non-nullable and has no initializer, so you get a compile error.

One fix is to use explicit abstract getter/setter declarations like in the second example. But that’s a little verbose, so with null safety we also added support for explicit abstract field declarations:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
3

This behaves exactly like the second example. It simply declares an abstract getter and setter with the given name and type.

Working with nullable fields

These new features cover many common patterns and make working with

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 pretty painless most of the time. But even so, our experience is that nullable fields can still be difficult. In cases where you can make the field
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
82 and non-nullable, you’re golden. But in many cases you need to check to see if the field has a value, and that requires making it nullable so you can observe the
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6.

You might expect this to work:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
4

Inside

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
18, we check to see if
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
77 is
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. If not, we access it and end up calling
// Using null safety:
String alwaysReturns(int n) {
  if (n == 0) {
    return 'zero';
  } else if (n < 0) {
    throw ArgumentError('Negative values not allowed.');
  } else {
    if (n > 1000) {
      return 'big';
    } else {
      return n.toString();
    }
  }
}
2 on it. Unfortunately, this is not allowed. Flow-based type promotion does not apply to fields because the static analysis cannot prove that the field’s value doesn’t change between the point that you check for
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 and the point that you use it. (Consider that in pathological cases, the field itself could be overridden by a getter in a subclass that returns
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 the second time it is called.)

So, since we care about soundness, fields don’t promote and the above method does not compile. This is annoying. In simple cases like here, your best bet is to slap a

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 on the use of the field. It seems redundant, but that’s more or less how Dart behaves today.

Another pattern that helps is to copy the field to a local variable first and then use that instead:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
5

Since the type promotion does apply to locals, this now works fine. If you need to change the value, just remember to store back to the field and not just the local.

For more information on handling these and other type promotion issues, see Fixing type promotion failures.

Nullability and generics

Like most modern statically-typed languages, Dart has generic classes and generic methods. They interact with nullability in a few ways that seem counter-intuitive but make sense once you think through the implications. First is that “is this type nullable?” is no longer a simple yes or no question. Consider:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
6

In the definition of

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
25, is
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
26 a nullable type or a non-nullable type? As you can see, it can be instantiated with either kind. The answer is that
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
26 is a potentially nullable type. Inside the body of a generic class or method, a potentially nullable type has all of the restrictions of both nullable types and non-nullable types.

The former means you can’t call any methods on it except the handful defined on Object. The latter means that you must initialize any fields or variables of that type before they’re used. This can make type parameters pretty hard to work with.

In practice, a few patterns show up. In collection-like classes where the type parameter can be instantiated with any type at all, you just have to deal with the restrictions. In most cases, like the example here, it means ensuring you do have access to a value of the type argument’s type whenever you need to work with one. Fortunately, collection-like classes rarely call methods on their elements.

In places where you don’t have access to a value, you can make the use of the type parameter nullable:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
7

Note the

// Using null safety:
int topLevel = 0;

class SomeClass {
  static int staticField = 0;
}
6 on the declaration of
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
55. Now the field has an explicitly nullable type, so it is fine to leave it uninitialized.

When you make a type parameter type nullable like

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
30 here, you may need to cast the nullability away. The correct way to do that is using an explicit
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
31 cast, not the
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 operator:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
8

The

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 operator always throws if the value is
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6. But if the type parameter has been instantiated with a nullable type, then
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 is a perfectly valid value for
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
26:

// Without null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString);
}
9

This program should run without error. Using

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
31 accomplishes that. Using
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 would throw an exception.

Other generic types have some bound that restricts the kinds of type arguments that can be applied:

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
0

If the bound is non-nullable, then the type parameter is also non-nullable. This means you have the restrictions of non-nullable types—you can’t leave fields and variables uninitialized. The example class here must have a constructor that initializes the fields.

In return for that restriction, you can call any methods on values of the type parameter type that are declared on its bound. Having a non-nullable bound does, however, prevent users of your generic class from instantiating it with a nullable type argument. That’s probably a reasonable limitation for most classes.

You can also use a nullable bound:

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
1

This means that in the body of the class you get the flexibility of treating the type parameter as nullable, but you also have the limitations of nullability. You can’t call anything on a variable of that type unless you deal with the nullability first. In the example here, we copy the fields in local variables and check those locals for

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 so that flow analysis promotes them to non-nullable types before we use
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
40.

Note that a nullable bound does not prevent users from instantiating the class with non-nullable types. A nullable bound means that the type argument can be nullable, not that it must. (In fact, the default bound on type parameters if you don’t write an

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
41 clause is the nullable bound
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
35.) There is no way to require a nullable type argument. If you want uses of the type parameter to reliably be nullable and be implicitly initialized to
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6, you can use
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
30 inside the body of the class.

Core library changes

There are a couple of other tweaks here and there in the language, but they are minor. Things like the default type of a

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
45 with no
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
46 clause is now
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
14 instead of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
48. Fallthrough analysis in switch statements uses the new flow analysis.

The remaining changes that really matter to you are in the core libraries. Before we embarked on the Grand Null Safety Adventure, we worried that it would turn out there was no way to make our core libraries null safe without massively breaking the world. It turned out not so dire. There are a few significant changes, but for the most part, the migration went smoothly. Most core libraries either did not accept

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 and naturally move to non-nullable types, or do and gracefully accept it with a nullable type.

There are a few important corners, though:

The Map index operator is nullable

This isn’t really a change, but more a thing to know. The index

// Using null safety:
String alwaysReturns(int n) {
  if (n == 0) {
    return 'zero';
  } else if (n < 0) {
    throw ArgumentError('Negative values not allowed.');
  } else {
    if (n > 1000) {
      return 'big';
    } else {
      return n.toString();
    }
  }
}
0 operator on the Map class returns
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 if the key isn’t present. This implies that the return type of that operator must be nullable:
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
52 instead of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
53.

We could have changed that method to throw an exception when the key isn’t present and then given it an easier-to-use non-nullable return type. But code that uses the index operator and checks for

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 to see if the key is absent is very common, around half of all uses based on our analysis. Breaking all of that code would have set the Dart ecosystem aflame.

Instead, the runtime behavior is the same and thus the return type is obliged to be nullable. This means you generally cannot immediately use the result of a map lookup:

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
2

This gives you a compile error on the attempt to call

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
5 on a nullable string. In cases where you know the key is present you can teach the type checker by using
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18:

// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
3

We considered adding another method to Map that would do this for you: look up the key, throw if not found, or return a non-nullable value otherwise. But what to call it? No name would be shorter than the single-character

// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18, and no method name would be clearer than seeing a
// Hypothetical unsound null safety:
bad(String? maybeString) {
  print(maybeString.length);
}

main() {
  bad(null);
}
18 with its built-in semantics right there at the call site. So the idiomatic way to access a known-present element in a map is to use
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
59. You get used to it.

No unnamed List constructor

The unnamed constructor on

// Without null safety:
String missingReturn() {
  // No return.
}
5 creates a new list with the given size but does not initialize any of the elements. This would poke a very large hole in the soundness guarantees if you created a list of a non-nullable type and then accessed an element.

To avoid that, we have removed the constructor entirely. It is an error to call

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
61 in null safe code, even with a nullable type. That sounds scary, but in practice most code creates lists using list literals,
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
62,
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
63, or as a result of transforming some other collection. For the edge case where you want to create an empty list of some type, we added a new
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
64 constructor.

The pattern of creating a completely uninitialized list has always felt out of place in Dart, and now it is even more so. If you have code broken by this, you can always fix it by using one of the many other ways to produce a list.

Cannot set a larger length on non-nullable lists

This is little known, but the

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
65 getter on
// Without null safety:
String missingReturn() {
  // No return.
}
5 also has a corresponding setter. You can set the length to a shorter value to truncate the list. And you can also set it to a longer length to pad the list with uninitialized elements.

If you were to do that with a list of a non-nullable type, you’d violate soundness when you later accessed those unwritten elements. To prevent that, the

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
65 setter will throw a runtime exception if (and only if) the list has a non-nullable element type and you set it to a longer length. It is still fine to truncate lists of all types, and you can grow lists of nullable types.

There is an important consequence of this if you define your own list types that extend

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
68 or apply
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
69. Both of those types provide an implementation of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
70 that previously made room for the inserted element by setting the length. That would fail with null safety, so instead we changed the implementation of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
70 in
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
69 (which
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
68 shares) to call
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
74 instead. Your custom list class should provide a definition of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
74 if you want to be able to use that inherited
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
70 method.

Cannot access Iterator.current before or after iteration

The

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
77 class is the mutable “cursor” class used to traverse the elements of a type that implements
// Using null safety:
makeCoffee(String coffee, [String? dairy]) {
  if (dairy != null) {
    print('$coffee with $dairy');
  } else {
    print('Black $coffee');
  }
}
23. You are expected to call
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
79 before accessing any elements to advance to the first element. When that method returns
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
80, you have reached the end and there are no more elements.

It used to be that

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
81 returned
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 if you called it either before calling
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
79 the first time or after iteration finished. With null safety, that would require the return type of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
81 to be
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
85 and not
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
86. That in turn means every element access would require a runtime
// Using null safety:
requireStringNotObject(String definitelyString) {
  print(definitelyString.length);
}

main() {
  Object maybeString = 'it is';
  requireStringNotObject(maybeString as String);
}
6 check.

Those checks would be useless given that almost no one ever accesses the current element in that erroneous way. Instead, we have made the type of

// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
81 be
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
86. Since there may be a value of that type available before or after iterating, we’ve left the iterator’s behavior undefined if you call it when you aren’t supposed to. Most implementations of
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
77 throw a
// Hypothetical unsound null safety:
requireStringNotNull(String definitelyString) {
  print(definitelyString.length);
}

main() {
  String? maybeString = null; // Or not!
  requireStringNotNull(maybeString);
}
91.

Summary

That is a very detailed tour through all of the language and library changes around null safety. It’s a lot of stuff, but this is a pretty big language change. More importantly, we wanted to get to a point where Dart still feels cohesive and usable. That requires changing not just the type system, but a number of other usability features around it. We didn’t want it to feel like null safety was bolted on.

The core points to take away are:

  • Types are non-nullable by default and made nullable by adding

    // Using null safety:
    int topLevel = 0;
    
    class SomeClass {
      static int staticField = 0;
    }
    
    6.

  • Optional parameters must be nullable or have a default value. You can use

    // Hypothetical unsound null safety:
    requireStringNotNull(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      String? maybeString = null; // Or not!
      requireStringNotNull(maybeString);
    }
    
    09 to make named parameters non-optional. Non-nullable top-level variables and static fields must have initializers. Non-nullable instance fields must be initialized before the constructor body begins.

  • Method chains after null-aware operators short circuit if the receiver is

    // Using null safety:
    requireStringNotObject(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      Object maybeString = 'it is';
      requireStringNotObject(maybeString as String);
    }
    
    6. There are new null-aware cascade (
    // Hypothetical unsound null safety:
    requireStringNotNull(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      String? maybeString = null; // Or not!
      requireStringNotNull(maybeString);
    }
    
    95) and index (
    // Hypothetical unsound null safety:
    requireStringNotNull(String definitelyString) {
      print(definitelyString.length);
    }
    
    main() {
      String? maybeString = null; // Or not!
      requireStringNotNull(maybeString);
    }
    
    96) operators. The postfix null assertion “bang” operator (
    // Hypothetical unsound null safety:
    bad(String? maybeString) {
      print(maybeString.length);
    }
    
    main() {
      bad(null);
    }
    
    18) casts its nullable operand to the underlying non-nullable type.

  • Flow analysis lets you safely turn nullable local variables and parameters into usable non-nullable ones. The new flow analysis also has smarter rules for type promotion, missing returns, unreachable code, and variable initialization.

  • The

    // Hypothetical unsound null safety:
    bad(String? maybeString) {
      print(maybeString.length);
    }
    
    main() {
      bad(null);
    }
    
    82 modifier lets you use non-nullable types and
    // Using null safety:
    makeCoffee(String coffee, [String? dairy]) {
      if (dairy != null) {
        print('$coffee with $dairy');
      } else {
        print('Black $coffee');
      }
    }
    
    52 in places you otherwise might not be able to, at the expense of runtime checking. It also gives you lazy-initialized fields.

  • The

    // Without null safety:
    String missingReturn() {
      // No return.
    }
    
    5 class is changed to prevent uninitialized elements.

Finally, once you absorb all of that and get your code into the world of null safety, you get a sound program that the compilers can optimize and where every place a runtime error can occur is visible in your code. We hope you feel that’s worth the effort to get there.