flutterdartmathics

How can I take string input character by character without return key? in dart


user will enter a string and i need to read that string character by character in dart.

Here is my code.

import 'dart:io';

void main() {
  int counter = int.parse(stdin.readLineSync());
  while (counter > 0) {
//here i need help to take a character not all string
    String twoNumbers = stdin.readLineSync();
    var splitNumber = twoNumbers.split(RegExp(r'\s+'));
///////////////////////////////////////////////////////////////////////
    String first = splitNumber[0];
    String second = splitNumber[1];
    if (second.length > first.length) {
      print("nao encaixa");
    } else if (first == second) {
      print("encaixa");
    } else if (first.substring(first.length - second.length) == second) {
      print("encaixa");
    } else {
      print("nao encaixa");
    }
    counter--;
  }
}

Solution

  • You can enumerate stdin directly to get the input instead of using readLine. You'll need to set lineMode=false to avoid the input being buffered until a newline arrives though:

    import 'dart:io';
    
    Future<void> main() async {
      // Don't wait for newlines.
      stdin.lineMode = false;
    
      // Suppress characters being printed automatically as the user types them
      // because we will print them ourselves (below).
      stdin.echoMode = false;
    
      // Enumerate stdin as characters arrive.
      await for (var input in stdin) {
        stdout.write('(${String.fromCharCodes(input)})');
      }
    }
    

    This just prints each character you press surrounde by parenthesis.