Search code examples
dartdart-null-safety

In the absence of a `pubspec.yaml` file, what determines whether I'm opting in to null safety?


I understand that if I cd /tmp and then dart create code, I get environment:<newline> sdk: '>=2.10.0 <3.0.0' in /tmp/code/pubspec.yaml, which tells me that even though I'm running Dart v. 2.12.3, this (default) configuration does not opt into null safety by default.

But what if I create an empty directory (mkdir /tmp/code), generate a one-liner program (echo "String a; " > /tmp/code/prog.dart), chdir (cd /tmp/code), then run (dart prog.dart), where will dart look for .dart_data/package_config.json and package_config.json?

Update

I'm starting to suspect that the absence of a pubspec.yaml is not a sanctioned use case for Dart programming. The presence of pubspec.yaml is the only way that a package can be installed, for example (dart pub add <package-name>). The ransom result I'm getting (with null safety in one directory; without in another) remains a puzzle, but perhaps if pubspec.yaml is omitted, then consistency might be too much to ask for.


Solution

  • The language-version marked in your .dart_tool/package_config.json file determines whether you have null safety. If the language version for your package is 2.12 or above, null safety is enabled.

    That file is generated by Pub when you run dart pub get or dart pub upgrade, based on your pubspec.yaml file, and the pubspec files of your resolved dependencies.

    Each Dart library can override the language version for that library by adding a //@dart=2.9 comment at the start of a library (and every part file of the library, if it uses parts).

    If you have no package_config.json file, the current default is to look for an old-style .packages file. If one is found, all language versions are set to 2.7, the language version of the SDK before introducing the package_config.json file and language versioning. Dart will stop looking for this old file eventually.

    (The .dart_tool library and .packages file is searched for in the directory of the Dart file you're running, then in each parent directory of this until reaching the root, or until finding something).

    If no .packages file is found either, the default is that you are using the most recent language version supported by the compiler. That likely means null safety is enabled. You can use a //@dart=2.9 comment to disable it (and all other later language features).