2

please I am new to dart and I want to create a simple program to accept two numbers from the user and sum up the two numbers.

However, when I run the code below, I encounter into an error.

Code

import 'dart:io';
import 'dart:math';

void main() {
print("enter num1: ");
String num1 = stdin.readLineSync();
print("enter num2: ");
String num2 = stdin.readLineSync();
print(int.parse(num1) + int.parse(num2));

}

Screenshot

Screenshot of the error

1 Answers1

1

stdin.readLineSync(); may return null if no input is given.

You variable expects only values of the type String on the other hand.

Fix this by adding a ? at the end of your variable name to make it nullable:

String? num1 = stdin.readLineSync();

Before using it later make sure it is not null:

if (num1 != null) {
   ...
}
Alexander Belokon
  • 1,452
  • 2
  • 17
  • 37
  • It worked! By the way, I was following this tutorial on youtube, here's the instructors code. https://i.stack.imgur.com/VQECh.png My problem is, I tried running the same code in my editor and encountered an error. – thebigbrownBox Apr 20 '21 at 09:23
  • 1
    He uses an older dart version, null safety came with dart version 2.12: https://dart.dev/null-safety – Alexander Belokon Apr 20 '21 at 09:28