0

I actually don't know how to take a integer input from the input console. Then I tried this after a little research.

My Code:

import 'dart:io';

void main() {
  stdout.write("Enter a number: ");
  int num1 = int.parse(stdin.readLineSync());
  print(num1);
}
  • But it doesn't work, showing an error message,
 ERROR: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
  • Then finally I came to know that in dart2.12+ versions dart introduced null safety. Any suggestion to do it properly in the null safety environment.
Uday Kiran
  • 77
  • 4

2 Answers2

1

The readLineSync() method returns a String?. The ? symbol indicates this variable may be null.

On the other hand, the int.parse() method expects a String, without the ? symbol. This means it doesn't know how to handle if the result from the readLine method comes null.

The easiest way to solve this is to give a default value in case the result comes null:

int num1 = int.parse(stdin.readLineSync() ?? '0');

The ?? operator makes the expression evaluates to the right side, if the left side is null. So giving it a default value it won't have to bother with a nullable type.

There are other operators you can use. You can read more about it in the Dart documentation about it.

Naslausky
  • 3,443
  • 1
  • 14
  • 24
0

Try this

import 'dart:io';

void main()
{
    // Asking for favourite number
    print("Enter your favourite number:");

    // Scanning number
    int n = int.parse(stdin.readLineSync());

    // Printing that number
    print("Your favourite number is $n");
}

If this not work I think you should try this answer link here

Divyesh
  • 2,085
  • 20
  • 35