-1

i just update my dart-sdk to 2.12.0 then error happen

import 'dart:io';
void main() {
  var waktuNow = DateTime.now();
  var waktuSekarang = waktuNow.year;
  stdout.write('Masukkan tahun kelahiran kamu : ');
  var tahunLahir = int.parse(stdin.readLineSync());
  hitungTahun(waktuSekarang, tahunLahir);
}

void hitungTahun(int a, int b) {
  var lahir = a - b;
  print('umur kamu : $lahir ');
}

error: The argument type 'String?' can't be assigned to the parameter type 'String'. (argument_type_not_assignable at [myapps] bin\coba2.dart:6)

how input int in dart 2.12.0 ?

julemand101
  • 28,470
  • 5
  • 52
  • 48
arcahyadi
  • 23
  • 6
  • 1
    I will recommend you to read about the null safety feature introduced in Dart 2.12. You can start here: https://dart.dev/null-safety – julemand101 Apr 22 '21 at 09:30
  • 3
    Does this answer your question? [Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't](https://stackoverflow.com/questions/66798782/error-the-argument-type-string-cant-be-assigned-to-the-parameter-type-stri) – Patrick O'Hara Apr 22 '21 at 10:10
  • thanks @PatrickO'Hara, is there a way of inputting an int/number than use readlinesnyc in dart ? im new in dart – arcahyadi Apr 22 '21 at 10:32
  • Not that I know of, use `readLineSync` ans `tryParse`. – Patrick O'Hara Apr 22 '21 at 17:15

1 Answers1

1

This is because you are now using null safety in Dart. You now need to be explicit in what variables can be null and also ensure those potentially nullable variables are "null checked"

stdin.readLineSync() can potentially return a null value. So you need to check for this case.

var s = stdin.readLineSync();
if(s != null) {
  var tahunLahir = int.parse(s);
  hitungTahun(waktuSekarang, tahunLahir);
}

You should also be careful of int.parse as this can through errors. If you're not 100% sure that you'll always get a "parsable" int. Use int.tryParse which also can return null. So further checks are required.

James
  • 2,516
  • 2
  • 19
  • 31
  • ahh, thank you so much, is there way of inputting an int other than use readlinesync? like using age = data.nextInt; in java – arcahyadi Apr 22 '21 at 10:04
  • From looking around it doesn't look like that's an option, sadly. https://stackoverflow.com/questions/55007696/how-to-get-console-integer-input-from-user-in-a-dart-program/55008738 – James Apr 22 '21 at 10:31
  • so, the only way inputting data in dart is use readlinesync ? im new in dart – arcahyadi Apr 22 '21 at 10:41