Home > Blockchain >  Dart: can i make a recursion end after meeting a condition
Dart: can i make a recursion end after meeting a condition

Time:01-19

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');

CodePudding user response:

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');
}
  •  Tags:  
  • Related