-2

how i fix these problem and make x and y to can sum it ,because the vs code tell me the x and y does not Undefined name 'y' and Undefined name 'x'

import 'dart:io';

void main() {
  print('enter your first number ');
  var s = stdin.readLineSync();
//for null safety
  if (s != null) {
    int x = int.parse(s);
  }

  print('enter your second number');

  var a = stdin.readLineSync();

  if (a != null) {
    int y = int.parse(a);
  }
  print('the sum is');
//here can not see the x and y varibale how i can put it 
  int res = x + y;
  print(res);
}
rioV8
  • 24,506
  • 3
  • 32
  • 49
Yous y
  • 41
  • 6

2 Answers2

1
if (s != null) {
    int x = int.parse(s);
  }

Means here x is only available inside if statement.

Variables that are out of the scope to perform int res = x + y;.

You can provide default value or use late

import 'dart:io';

void main() {
  print('enter your first number ');
  var s = stdin.readLineSync();
  late int x ,y; // I pefer providing default value x=0,y=0
//for null safety
  if (s != null) {
      x = int.parse(s);
  }

  print('enter your second number');

  var a = stdin.readLineSync();

  if (a != null) {
     y = int.parse(a);
  }
  print('the sum is');
 
  int res = x + y;
  print(res);
}

More about lexical-scope on dart.dev and on SO.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Using `late` is not a good idea here since `x` and `y` will remain uninitialized if `stdin.readLineSync()` returns `null` on EOF. – jamesdlin Jan 15 '22 at 09:46
1

In some cases, your variable might not get initialized with an int and it can be left as a null value, like in the if statement in your code (If the statement doesn't get triggered then the variables will be set as null). And dart with null safety ON doesn't allow that.

SOL: Initialize your variable with a default value or use the late keyword in front of them, while declaring.

var a=0;
var b=0;

OR

late var a;
late var b;
Kyoto
  • 308
  • 4
  • 4