0

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.

Saad Ebad
  • 206
  • 5
  • 16

4 Answers4

0

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

Sofiane
  • 1
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 23 '22 at 06:47
0

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");
}
Saad Ebad
  • 206
  • 5
  • 16
0

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);
YP pinthu
  • 1
  • 1
0

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
developerjamiu
  • 590
  • 8
  • 19