目錄

健全的空安全

Dart 語言要求使用健全的空安全特性。

空安全會在編譯期防止意外存取 null 變數的錯誤的產生。

例如,如果一個方法需要整型結果,卻接收到了 null,你的應用會出現執行時錯誤。這類空參考錯誤在以前除錯是非常困難的。

有了健全的空安全體系,變數需要有預設值,即 Dart 認為變數是「非空」的。它們可以賦予與定義的型別相同型別的任意值(例如 int i = 42),且永遠不能被設定為 null。你可以指定一個類別型為可空(例如 int? i),這類變數只能包含對應型別的值或者 null

健全的空安全透過對非空變數的未被初始化或以 null 初始化的情況進行標記,把潛在的 執行時錯誤 轉變成了 編輯時 的分析錯誤。這樣的特性讓你在開發應用的過程中就可以修復這類錯誤:

  • 沒有以非空的值初始化

  • 賦了 null 值。

這些檢查讓你能在建構你的應用前就修復這些錯誤。

透過範例程式碼介紹空安全

有了空安全,下面程式碼中所有的變數都是非空的:

// With null safety, none of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();

若你想讓變數可以為 null,只需要在型別聲明後加上 ?

int? aNullableInt = null;

空安全的原則

Dart 的空安全支援基於以下三條核心原則:

  • 預設不可空。除非你將變數顯式宣告為可空,否則它一定是非空的型別。我們在研究後發現,非空是目前的 API 中最常見的選擇,所以選擇了非空作為預設值。

  • 完全可靠。Dart 的空安全是非常可靠的,意味著編譯期間包含了很多最佳化。如果型別系統推斷出某個變數不為空,那麼它 永遠 不為空。當你將整個專案和其依賴完全遷移至空安全後,你會享有健全性帶來的所有優勢—— 更少的 BUG、更小的二進位制檔案以及更快的執行速度。

Dart 3 and null safety

Dart 3 has built-in sound null safety. Dart 3 prevents code without it from running.

To learn how to migrate to Dart 3, check out the Dart 3 migration guide. Packages developed without null safety support cause issues when resolving dependencies:

$ dart pub get

Because pkg1 doesn't support null safety, version solving failed.
The lower bound of "sdk: '>=2.9.0 <3.0.0'" must be 2.12.0 or higher to enable null safety.

Libraries incompatible with Dart 3 cause analysis or compilation errors.

$ dart analyze .
Analyzing ....                         0.6s

  error • lib/pkg1.dart:1:1 • The language version must be >=2.12.0. 
  Try removing the language version override and migrating the code.
  • illegal_language_version_override
$ dart run bin/my_app.dart
../pkg1/lib/pkg1.dart:1:1: Error: Library doesn't support null safety.
// @dart=2.9
^^^^^^^^^^^^

To resolve these issues:

  1. Check for null safe versions of any packages you installed from pub.dev
  2. migrate all of your source code to use sound null safety.

Dart 3 can be found in the stable channels for Dart and Flutter. To learn more, check out the download page for details. To test your code for Dart 3 compatibility, use Dart 3 or later.

$ dart --version                     # make sure this reports 3.0.0-417.1.beta or higher
$ dart pub get / flutter pub get     # this should resolve without issues
$ dart analyze / flutter analyze     # this should pass without errors

If the pub get step fails, check the status of the dependencies.

If the analyze step fails, update your code to resolve the issues listed by the analyzer.

啟用和禁用空安全

在 Dart 2.12 到 2.19 中,你需要手動啟用空安全。 Dart 2.12 之前的 SDK 版本不提供空安全。

想要啟用健全空安全,你需要將 SDK 的最低版本約束 設定為 2.12 或者更高的 語言版本。例如,你的 pubspec.yaml 可以設定為如下的限制:

environment:
  sdk: '>=2.12.0 <3.0.0'

Migrating existing code

遷移現有的 package 或應用

沒有加入空安全支援的 Dart 程式碼可以遷移到使用空安全。我們建議使用 Dart SDK 2.12 到 2.19 版本中包含的 dart migrate 工具。

$ cd my_app
$ dart migrate

你可以閱讀 遷移指南 來學習如何遷移你的程式碼至空安全。

學習更多

想了解關於空安全的更多內容,可檢視以下的資源內容: