Getting input from the console using 'Dart'

How to take input from the user by using Dart language

Table of contents

No heading

No headings in the article.

Before starting let's have a quick and short introduction to dart.

What is Dart?

  • So, Dart is a General-Purpose Programming Language developed by Google

  • It is also an Object-Oriented Programming language mostly designed for client-side development.

  • And an important language for Flutter.

  • It is somewhat similar, to Java and python and it is open source too.

Importance and Uses of learning Dart

Firstly, Dart is pretty easy to learn if you know Java then it's a plus point. It can solve many problems, efficiently. Dart syntax is simple It is used in both mobile and web development one can create many apps and supports much of Google's revenue.

Future scope

Flutter is the most & will be a widespread and useful app development platform in upcoming years. So clearly, Dart is having a shining future!☀

Now, moving on towards our program

The very first step is to import the library that is 'dart.io' adding this import statement will extract the components and it is written at top of the code editor. Every program resides in the main method to dart's main method or entry point is void main()

import 'dart:io'
void main(){  
 // Your program goes here
print('Enjoy the process');
}

So far so good let's dive into some more concepts needed for getting input from the console. If you know or are familiar with Java/ C++'s syntax then there is a concept of standard input (stdin), standard output (stdout)

Dart also has the same as it is somewhat similar to java.

stdin() - It takes text as input

stdin.readLineSync() - This method is to take standard input from the console using .readLineSync()

stdout() - It prints output

stdout.writeln()- Is used to display output to the console or we can simply use the print statement also.

Let's start taking String as the input from console ✌ -

import 'dart:io';  // importing library

void main() {   

  stdout.writeln('Enter your name: ');   //Asking the name as output

  String? name = stdin.readLineSync();  //Taking input from user

  print("Your name is $name");        //Priniting name

}

Pretty good!🌼

Now let's start taking Integer as the input from the console -

import 'dart:io';  // importing library

void main() {   

print("Enter your favourite number:");  
int? n = int.parse(stdin.readLineSync()!);  // Scanning number & Here '?' and ' ! ' are for null safety
print("Your favourite number is $n");    

}

Hope it was useful to you! That’s all for this blog.

Feedback and comment are much appreciated ❤

Twitter - twitter.com/WasuSamruddhi

Github - github.com/ambivert-sam

LinkedIn - linkedin.com/in/samruddhi-wasu-a7855a204

Did you find this article valuable?

Support Samruddhi Wasu by becoming a sponsor. Any amount is appreciated!