How to take integer input from user in dart

964 Views Asked by At

i am new in dart and just want to know how to take integer input from user in dart with null safety. i found out a way to take number input from dart which is:

String? chossenNumber =  stdin. readLineSync();
   if(chossenNumber !=null)
   {
     int number = int.parse(chossenNumber);
   }

but i am unable to use number variable outside of the scope. Please tell me a way to solve this issue.

4

There are 4 best solutions below

0
On

The solution of it very simple just take input of number as String i.e

String? chossenNumber =  stdin. readLineSync();

and when you want to use this variable parse it to the 'int' i.e

if(int.parse(chossenNumber) <100)
{
print("Your Statement");
}
1
On

You can define the variable at the top of the class and initialize it here so you will be able to use it everywhere in the class

0
On

You can define the variable at the top of the class

var name,age;

print('Enter Your Age : ');

age=int.parse(stdin.readLineSync()!) ;

print(age);
0
On

After retrieving chosenNumber for the stdin

String? chosenNumber =  stdin.readLineSync();

You can declare number at the top of the method as a nullable integer, for example:

int? number;

Then after your check, you can initialize number

if (chosenNumber != null) {
  number = int.parse(chosenNumber);
}

This way you will have access to number outside the if scope

Summary

String? chosenNumber =  stdin.readLineSync();

int? number;

if (chosenNumber != null) {
  number = int.parse(chosenNumber);
}

print(number); // number is accessible here
number = 19; // and here