0
import 'dart:math';
import "dart:io";
void main() {
  print('enter first number:');
  var num1 = stdin.readLineSync();
  print('enter second number:');
  var num2 = stdin.readLineSync();
  print(num1 + num2);
}

This is what I keep getting--

Error: A value of type 'String?' can't be assigned to a variable of type 'String' because 'String?' is nullable and 'String' isn't, and 'Error: Operator '+' cannot be called on 'String?' because it is potentially null'

I have tried using string instead of var and also string?

Stack Underflow
  • 2,363
  • 2
  • 26
  • 51
Emmynew
  • 1
  • 2

2 Answers2

1

Convert the input strings to numbers and make sure they are not null.

The error you were getting was caused by Dart's null safety checks. You can ensure the variables will not be null by providing a default value to them in the event that stdin.readLineSync() returns null by using the ?? operator to check for null and use the operand on the right if it is.

import 'dart:io';

void main() {
  print('enter first number:');
  // Use int.parse(String) to convert input to a number
  var num1 = int.parse(stdin.readLineSync() ?? '0');

  print('enter second number:');
  var num2 = int.parse(stdin.readLineSync() ?? '0');
  print(num1 + num2);
}

If you want a double rather than int, double has a similar static method for converting a string to a number. https://api.dart.dev/stable/2.15.1/dart-core/double/parse.html

Also see https://dart.dev/guides/libraries/library-tour#numbers

Stack Underflow
  • 2,363
  • 2
  • 26
  • 51
0

This should solve it

  void main() {
      print('enter first number:');
      var num1 = stdin.readLineSync() ?? '-';
      print('enter second number:');
      var num2 = stdin.readLineSync() ?? '-';
      print(num1 + num2);
    }
Eternity
  • 217
  • 1
  • 9