Issue
so, I’m collecting input and using a while loop with the condition (if user omits input say…) I am using this while loop for several input collection in the same code so i decided to write a function for it with a couple parameters, however after user skips input and later enters it, it doesn’t register, output should print "how are you $input"
however it just prints "how are you"
and leaves input blank
main() {
// First name
print('First name:');
var name1 = stdin.readLineSync();
void conds(name, shitbe) {
while (name.isEmpty) {
print('Field cannot be empty');
print(shitbe);
name = stdin.readLineSync();
}
}
conds(name1, 'First name:');
print('How are you $name1');
output should be like
PS C:\tools\Projects> dart playground.dart
First name:
Field cannot be empty
First name:
John
How are you John
PS C:\tools\Projects>
but this is what I’m getting after the first omission
PS C:\tools\Projects> dart test.dart
First name:
Field cannot be empty
First name:
John
How are you
PS C:\tools\Projects>
Solution
All variables in Dart is references to objects. When you give a variable as argument to a method, the variable is copied so we got a copy of this reference.
Inside the method, you can do whatever you want with this reference but if you change what object the reference/variable points to, this change will not be seen by the code calling your method.
So inside conds()
you are changing name
, which is an argument, to point to a new String
object you got from the user. But the caller of conds()
will not see the change of the name1
variable since the reference got copied into the method.
I would personally rewrite the code to something like this where the method handles all the interaction with the user and returns the String
afterwards.
import 'dart:io';
void main() {
// First name
final name = getInput('First name:');
print('How are you $name');
}
String getInput(String message) {
print(message);
var input = stdin.readLineSync();
while (input == null || input.isEmpty) {
print('Field cannot be empty');
print(message);
input = stdin.readLineSync();
}
return input;
}
Answered By – julemand101
Answer Checked By – Marilyn (BugsFixing Volunteer)