0

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> 
rioV8
  • 24,506
  • 3
  • 32
  • 49
  • 1
    This has nothing to do with a `while` loop. It's about your function reassigning a parameter (a local variable) and expecting that assignment to affect the caller. [Dart is pass-by-value](https://stackoverflow.com/q/25170094/). – jamesdlin Jan 20 '22 at 20:00

1 Answers1

0

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;
}
julemand101
  • 28,470
  • 5
  • 52
  • 48
  • omdssssss ^^ Thanksssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss a lotttttt, taken the advice to account as well, i didn't realise it copied the references and worked with them as such – public static void Main Jan 20 '22 at 20:08