How do you opt out of null safety in Dart?

3k views Asked by At

As of Dart 2.12.0, null safety is enabled by default.

The "Enabling null safety" section on dart.dev states the following:

Set the SDK constraints to require a language version that has null safety support. For example, your pubspec.yaml file might have the following constraints:

environment:
 sdk: ">=2.12.0-0 <3.0.0"

So now that it is enabled by default, how do we opt out of null safety and write code like before when our SDK constraint has >=2.12.0-0?
We might want to require a Dart version like this for a different language feature but not want to use NNBD.

1

There are 1 answers

0
creativecreatorormaybenot On BEST ANSWER

There is no way to not use NNBD in a file that uses Dart >=2.12.0=0.
Thus, you only have two options to opt out of null safety:

Opting out file by file

Even if your minimum SDK constraint is >=2.12.0=0, you can opt-out single files using per-library language version selection.

At the very top of your file before any imports etc., you can specify the Dart version the whole file should use:

// @dart=2.11
import 'dart:math';
...

This way, that file will be able to opt-out of null safety by using Dart 2.11.

Lower the SDK constraint

If you lower Dart SDK constraint is below 2.12.0-0, you are by default opting out of null safety:

environment:
 sdk: ">=2.11.0 <3.0.0"

Learn more by reading through the unsound null safety article on dart.dev.