Can someone tell me why I am getting a 'null' output after execution?

Issue

Can someone tell me why I am getting a ‘null’ output at the end of Result-1?

#When I return just ‘Exercise1() from the main, the null do not appear.
#But I am confused and want to know what is causing this null in the result.

main.dart

import 'exercises/exercise1.dart';

void main() {
  // return Exercise1();
  print(Exercise1());
}

exercise1.dart

import 'dart:io';

Exercise1() {
  stdout.write("What is your name? \n");
  String? name = stdin.readLineSync();

  stdout.write("Hi $name, What is your age? \n");
  int? age = int.parse(stdin.readLineSync().toString());

  int? yearsLeftFor100 = 100 - age;

  print("Hello $name, your age is $age");

  print("Hi $name, you will attain 100 years in another $yearsLeftFor100 years.");
}

Result-1: Run with print(Exercise1()) statement;

$ dart run main.dart
What is your name? 
John Doe
Hi John Doe, What is your age? 
31
Hello John Doe, your age is 31
Hi John Doe, you will attain 100 years in another 69 years.
null

Result-2: Run with return Exercise1() statement;

$ dart run main.dart
What is your name? 
John Doe
Hi John Doe, What is your age? 
31
Hello John Doe, your age is 31
Hi John Doe, you will attain 100 years in another 69 years.

Solution

Since you did not declare the return type of Exercise1(), it’s return type is dynamic.

Since you do not have a return statement in your method, the return type is void. Meaning it does not return anything.

Therefore, when you are printing out the return value of it’s invocation, you are seeing null.

Answered By – tomerpacific

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.