Null Safety in Flutter

Ankit dwivedi
2 min readDec 6, 2022

Hello folks,

Today we will see, How null safety works in dart?

First lets discuss what is null safety?

Null safety let’s your code run smoother and faster.

To understand null safety we need to know about two symbols related to it “? and !”.

for example our main function is

when we run this code will print “true” as result.

but what happen if we initialize isEat with null value

it shows error because currently bool variable only holds true/false value.

but what happened when we use ? during initialization.

isEat variable become nullable means, now it can hold null value and the program will run and print null.

Now let’s discuss about “ ! ”

! refers to not null means it tell about any variable that it is not null, let’s see in the code.

at line number 8 we will get error when we try to run the code because inside if we are passing the variable which is nullable but if only accept true or false, so it throws error. Here “ ! “ comes into picture.

If we use ! to tell isEat is not null anymore then this same program will run without an issue. let’s see in code.

Now, error goes away and program run successfully and print

I done my lunch

true

Be Aware !

What if isEat never falls into able condition and not set its value to true, and it has its default null value then what happen let’s see that one too.

This program won’t shows any error but at run time it throws an error, because isEat is actually null and we are telling isEat is not null, this gives us run time error of “Uncaught TypeError: Cannot read properties of null”.

So I hope you understand the use of “ ! and ? “ in flutter.

Thank you for reading :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ankit dwivedi
Ankit dwivedi

Written by Ankit dwivedi

Software developer ? ( Flutter || Dart || IOS ||C# || Nodejs || Kotlin || Java || Android ) : Writing

No responses yet

Write a response