Flutter Null Safety

The Ultimate Guide 🎯 to Null Safety in Flutter & Dart

Kushal Goel
FlutterFever
Published in
2 min readMay 16, 2021

--

Null Safety is Flutter’s New Feature 🎁 released recently in Flutter 2.0. It makes Flutter & Dart more Strict & Less Prone to Errors & Bugs 🐛 . Let's Decode it !!

Coding — Photo by Clément Hélardot on Unsplash

Note: If Reading Articles is not your Cup of Tea ️️️🍵, you can check it out in a more Visual & Eye — Pleasing format here.

So, What is Null Safety?

It means that variables can only be null if we say so. For Example

For example -

int aNullableInt; is Wrong &

int? aNullableInt; is Correct.

Operators in Null Safety

  • ? - This is used when you want to say that a value can be null. (Is also used as a Ternary Operator)
  • ! - This is used when you know that a nullable type is not null.
  • ?? - This is used to check if a value is null and if so return a default value. For eg. aNullableInt ?? 0;
  • ?. - It is used for safely accessing a property or a method of an object that might be null.
  • late - Used when you know that a non-nullable variable will be initialized before use later but is null for now.

Bonus Tip

If you have an App or a Package without Null Safety, just type the following command in the terminal and make it Null Safe !! -

$ dart migrate.

Assess your Null Safety Skills

Q) Which of the statements for getting John’s score is correct? (A or B ?)

Map<String, int> scores = {
'John': 98,
'Adam': 74,
'Bill': 88,
};

A) int johnsScore = scores['John'];

B) int? johnsScore = scores['John'];

What do you Think ? Answer in the Comments Below ?

Want to Try Null Safety ?

Go to the Null Safe Version of DartPad here.

This was all Null Safety had to offer. I hope you learned something new. Thanks for Reading this & I will see you in the next article !!

FlutterFever is an Immersive Environment for High-Quality Flutter Tutorials, Resources, Tips & Tricks to Build, Deploy and Market Beautiful and Performant Flutter Apps Effortlessly. Find more about it here.

--

--

Kushal Goel
FlutterFever

Passionate Developer 👨🏻‍💻 & Love to Explore New Technologies 📱