Search code examples
androidflutterdartsum

how put the varibale x and y defined to make sum function because i only have this way for null safety


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);
}

Solution

  • 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.