Unable to Accept User Input In Dart

Viewed 276

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 Answers

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) {
   ...
}
Related