[SOLVED] Dart: can i make a recursion end after meeting a condition

Issue

I wrote a function for name collection, if the user omits the input, the function returns "you skipped .." and asks for it again, but the function keeps recursing even after i enter an input, it still keeps asking over and over like i left it blank

void main() {
  print('what is your name bro:');
  String? name = stdin.readLineSync();
  void ncon() {
    if (name == '') {
      print('Name can\'t be empty \n\nWhat is your name bro:');
      String? name = stdin.readLineSync();
      ncon();

    }
  }

  ncon();
  print('How are you $name');
}

I want the recursion to end if user finally inputs a name and just skip to print('How are you $name');

Solution

Don’t make this recursive. Use a while loop!

void main() {
  print('what is your name bro:');
  var name = stdin.readLineSync()!;

  while (name.isEmpty) {
    print('Name can\'t be empty \n\nWhat is your name bro:');
    name = stdin.readLineSync()!;
  }
  print('How are you $name');
}

Answered By – Kevin Moore

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *