What is null and void in Dart, Flutter

The terms null and void, both have special meaning in Dart and Flutter. We have already discussed null safety in Dart. But we have not discussed null and void jointly.

In Natural language, null and void means ineffective, or invalid. This idiom was first recorded in 1669. Therefore, this idiom has a historical importance.

However, in the programming world, both null and void have certain meaning and importance.

Let us consider a short Dart code.

void main() {
  
  bar(baz); // false
  
  baz.call(); // null
  
}

void foo() {
  String? aText;
  print(aText);
}
  
var baz = foo;
  
void bar(baz) {
    if (baz == null) {
    print('true');
  } else {
      print('false');
  }
}

In the above code, it is evident that void is not null.

The output clearly says that.

However, null is both a value and a pointer.

Let us modify the above code a little bit.

void main() {
  
  AnyClass anyObject = AnyClass();
  
  print(anyObject.thisIsNullable); // null
  
  print(anyObject.aNullInstanceVariable); // null
  
}

class AnyClass {
  String? thisIsNullable;
  ANullClass? aNullInstanceVariable;
  AnyClass({this.thisIsNullable});
}

class ANullClass {}

It clearly shows that NULL is a value.

Usually, when we use void as a function return type that does not return any value. But, when the function executes all the code inside, it should return this value.

People often get confused in this place.

It is better if we say that void function can execute some code. Or, follow some instructions.

Consider this code snippet.

void main() {
  
  print(greet('Json', 'Hello', null)); // Json says Hello
  
  say(); // Json says Hello
  
  print(greet('Json', 'Hello', 'Phone')); // Json says Hello with a Phone 
  
}

String greet(String from, String msg, String? device) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

void say() {
  print(greet('Json', 'Hello', null));
}

It is again proved that null is a value. We can pass it as a value and change the output of the code.

On the other hand, void can call another function with a certain return type and give an output.

In previous section we have discussed VoidCallback in Flutter. That might give you more insight.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

Leave a Reply