How do I capture stdin (more than one line) to a String in Dart?


I have a Dart command-line program that want to be able to pipe data from the shell to the Dart program (e.g., cat file.txt | dart my_program.dart or accept input until the user uses Ctrl+d). Going through the tutorials online, the only documentation I found on saving input from the stdin was stdin.readLineSync(). However, as the name implies, this only reads the first line.

How can capture the entire contents of the stdin to a String? Also, would there be any security concerns if a user tries to pipe in an enormously large file? Is there a limit to how long the String can be? How can I safeguard against that?

Thanks for your help!


I studied the code of the stdin.readLineSync() and was able to modify it to fit my needs:

import 'dart:convert';
import 'dart:io';

String readInputSync({Encoding encoding: SYSTEM_ENCODING}) {
  final List input = [];
  while (true) {
    int byte = stdin.readByteSync();
    if (byte < 0) {
      if (input.isEmpty) return null;
  return encoding.decode(input);

void main() {
  String input = readInputSync();
  myFunction(input); // Take the input as an argument to a function

I needed to read synchronously from the stdin in order to pause the program until the entire stdin (until the end of file or Ctrl+d) was read.

Thanks for all your help! I don’t think I would have been able to figure it out without your help.

Answered By – Dariel Dato-on

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

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