The introduction of Null Safety marks a major milestone for the Dart language. Null Safety helps you avoid an entire class of problems by catching null errors during development rather than at runtime.
This article outlines what's changed, and shows how to use the new Null Safety features by example.
Null Safety is available as a stable release with Flutter 2.0, and is enabled by default for all projects created with Flutter 2.2. You can try it with Dartpad.
sponsor
Subscription Management for Flutter apps. RevenueCat gives you everything you need to build, analyze, and grow IAPs with just a few lines of code.
Some Context
Null References were first introduced in 1965 in the ALGOL programming language, and since then they have been adopted by most mainstream programming languages.
However, null errors are so common that null references have been called the The Billion Dollar Mistake.
Subscription Management for Flutter apps. RevenueCat gives you everything you need to build, analyze, and grow IAPs with just a few lines of code.
Conclusion
Null Safety is a major change for the Dart language, and it helps you write better and safer code, as long as you use it correctly.
For new projects, keep in mind all the syntax changes we covered. This may seem like a lot to take in, but it all boils down to this:
Every time you declare a variable in Dart, think about whether it should be nullable or not. This is extra work, but it will lead to better code and Dart will help you along the way.
For existing projects created before Null Safety, things are a bit more tricky and you have to migrate your code first. This involves multiple steps that should be followed in the right order. Here's a practical case study showing how to do this:
- Migrating a Flutter & Firebase app to Null Safety: A Case Study
If you want to learn Dart in-depth with a structured approach, consider taking my complete Dart course. This covers all the most important language features, including exercises, projects and extra materials:
The Complete Dart Guide. View CourseReferences
This article was mainly inspired by these sources:
- Announcing Dart 2.12
- What is Null Safety in Dart? | Stack Overflow
- Sound null safety | dart.dev
- Understanding null safety | dart.dev
Migration resources:
- Migrating to null safety | dart.dev
- Null Safety Migration Tooling | pub.dev
- How to migrate Dart code to Non-nullable [NNBD]? | Stack Overflow
Happy coding!