How to get console integer input from user in a dart program? - dart

I want to get integer input from console in dart but unable to do so . How do I do that?
main()
{
int n = stdin.readLineSync();
}

You need to parse string captured by stdin.readLineSync() using int.parse()
import 'dart:io';
void main() {
int n = int.parse(stdin.readLineSync());
}

Related

Compiler for dart

Is there any editor for dart.
I was trying to run my dart program at vscode it runs but did not print anything.
I was trying to take input from user and add it into a list of numbers and then show the list on console.
It takes the input but did not shown any list.
// Importing dart:io file
import 'dart:io';
void main() {
List<int> list = [5];
// Scanning number
for (var i = 0; i < list.length; i++) {
int? n = int.parse(stdin.readLineSync()!);
list.add(n);
}
// Here ? and ! are for null safety
// Printing that number
print("Your list $list");
}

How to take input from user in dart?

some changes in Dark 2.0 so refer this code.
void main() {
int n = int.parse(stdin.readLineSync()!); // stdin.readLineSync() used for int value
String? name = stdin.readLineSync()!; // stdin.readLineSync() used for String value
print("enter name: ${name}");
print("enter number: ${n}");
}
Do this instead:
import 'dart:io';
void main() {
int n = int.parse(stdin.readLineSync());
String name = stdin.readLineSync();
print("enter name: ${name}");
print("enter number: ${n}");
}
To take the string input you can use the following code
import "dart:io";
void main() {
print("enter name:");
String name = stdin.readLineSync()!;
print("your name is: $name");
}
To take the integer input you can use the following code
import "dart:io";
void main() {
print("enter number:");
int number= int.parse(stdin.readLineSync()!);
print("number you entered is: $num");
}
To print the srting input in integer you can use the following code
import "dart:io";
void main() {
print("enter string:");
String str = stdin.readLineSync()!;
print("number converted to int is ${int.parse(str)}");
}

Dart type that is implemented by everything

I'm not quite sure how to phrase this but I basically want to write a function like this:
import 'dart:async';
int countBroadcastStreams(List<Stream<Object>> streams) {
return streams.where((s) => s.isBroadcast).length;
}
void main() {
final a = StreamController<int>.broadcast();
final b = StreamController<String>.broadcast();
countBroadcastStreams([
a.stream,
b.stream,
]);
}
This works, however if I change one of the StreamControllers to StreamController<Null> then it doesn't because Null is the only type that doesn't inherit Object.
So my question is: which type should I use instead of Object so it works with Null too? dynamic seems to work, but is that the best option? Does it introduce additional runtime cost?
I don't think the problem comes from the Object type. Try to explicitly specify that the Stream objects can be null:
import 'dart:async';
int countBroadcastStreams(List<Stream<Object?>> streams) {
return streams.where((s) => s != null && s.isBroadcast).length;
}
void main() {
final a = StreamController<int>.broadcast();
final b = StreamController<Null>.broadcast();
print(countBroadcastStreams([
a.stream,
b.stream,
]));
}
// console log: 2
Specify the nullable type for the stream objects: List<Stream<Object**?**>> streams.

is there any function to choose Random character from a given string in DART

I am new to DART, and i would like to know is there any way to choose random characters from am given string in DART.
Any built-in functions available?
Thanks
Well, you can use the Random class from dart:math to make your own function:
import 'dart:math';
void main() {
print(getRandomLetter('Hello World'));
}
final _rnd = Random();
String getRandomLetter(String input) => input[_rnd.nextInt(input.length)];

How do I read console input / stdin in Dart?

How do I read console input from stdin in Dart?
Is there a scanf in Dart?
The readLineSync() method of stdin allows to capture a String from the console:
import 'dart:convert';
import 'dart:io';
void main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: utf8);
print(line?.trim() == '2' ? 'Yup!' : 'Nope :(');
}
Old version:
import 'dart:io';
main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: Encoding.getByName('utf-8'));
print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
}
The following should be the most up to date dart code to read input from stdin.
import 'dart:async';
import 'dart:io';
import 'dart:convert';
void main() {
readLine().listen(processLine);
}
Stream<String> readLine() => stdin
.transform(utf8.decoder)
.transform(const LineSplitter());
void processLine(String line) {
print(line);
}
import 'dart:io';
void main(){
stdout.write("Enter your name : ");
var name = stdin.readLineSync();
stdout.write(name);
}
Output
Enter your name : Jay
Jay
By default readLineSync() takes input as string. But If you want integer input then you have to use parse() or tryparse().
With M3 dart classes like StringInputStream are replaced with Stream, try this:
import 'dart:io';
import 'dart:async';
void main() {
print("Please, enter a line \n");
Stream cmdLine = stdin
.transform(new StringDecoder())
.transform(new LineTransformer());
StreamSubscription cmdSubscription = cmdLine.listen(
(line) => print('Entered line: $line '),
onDone: () => print(' finished'),
onError: (e) => /* Error on input. */);
}
As of Dart 2.12, null-safety is enabled, and stdin.readLineSync() now returns a String? instead of a String.
This apparently has been confusing a lot of people. I highly recommend reading https://dart.dev/null-safety/understanding-null-safety to understand what null-safety means.
For stdin.readLineSync() specifically, you can resolve this by checking for null first, which for local variables will automatically promote a String? to a String. Here are some examples:
// Read a line and try to parse it as an integer.
String? line = stdin.readLineSync();
if (line != null) {
int? num = int.tryParse(line); // No more error about `String?`.
if (num != null) {
// Do something with `num`...
}
}
// Read lines from `stdin` until EOF is reached, storing them in a `List<String>`.
var lines = <String>[];
while (true) {
var line = stdin.readLineSync();
if (line == null) {
break;
}
lines.add(line); // No more error about `String?`.
}
// Read a line. If EOF is reached, treat it as an empty string.
String line = stdin.readLineSync() ?? '';
Note that you should not blindly do stdin.readLineSync()!. readLineSync returns a String? for a reason: it returns null when there is no more input. Using the null assertion operator (!) is asking for a runtime exception.
Note that while calling stdin.readLineSync() your isolate/thread will be blocked, no other Future will be completed.
If you want to read a stdin String line asynchronously, avoiding isolate/thread block, this is the way:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// [stdin] as a broadcast [Stream] of lines.
Stream<String> _stdinLineStreamBroadcaster = stdin
.transform(utf8.decoder)
.transform(const LineSplitter()).asBroadcastStream() ;
/// Reads a single line from [stdin] asynchronously.
Future<String> _readStdinLine() async {
var lineCompleter = Completer<String>();
var listener = _stdinLineStreamBroadcaster.listen((line) {
if (!lineCompleter.isCompleted) {
lineCompleter.complete(line);
}
});
return lineCompleter.future.then((line) {
listener.cancel();
return line ;
});
}
All these async API readLine*() based solutions miss the syntactic sugar which gives you the ability to do everything without synchronous blocking, but written like synchronous code. This is even more intuitive coming from other languages where you write code to execute synchronously:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
var lines = stdin.transform(utf8.decoder).transform(const LineSplitter());
await for (final l in lines) {
print(l);
}
print("done");
}
The key takeaway here is to make use of async and await:
async on your method is required, as you're using await to interface with asynchronous API calls
await for is the syntax for doing "synchronous-like" code on a Stream (the corresponding syntax for a Future is just await).
Think of await like "unwrapping" a Stream/Future for you by making the following code execute once something is available to be handled. Now you're no longer blocking your main thread (Isolate) to do the work.
For more information, see the Dart codelab on async/await.
(Sidenote: The correct way to declare any return value for an async function is to wrap it in a Future, hence Future<void> here.)
You can use the following line to read a string from the user:
String str = stdin.readLineSync();
OR the following line to read a number
int n = int.parse(stdin.readLineSync());
Consider the following example:
import 'dart:io'; // we need this to use stdin
void main()
{
// reading the user name
print("Enter your name, please: ");
String name = stdin.readLineSync();
// reading the user age
print("Enter your age, please: ");
int age = int.parse(stdin.readLineSync());
// Printing the data
print("Hello, $name!, Your age is: $age");
/* OR print in this way
* stdout.write("Hello, $name!, Your age is: $age");
* */
}
You could of course just use the dcli package and it's ask function
Import 'package: dcli/dcli.dart':
Var answer = ask('enter your name');
print (name);
Use the named validator argument to restrict input to integers.
To read from the console or terminal in Dart, you need to:
import 'dart:io' library
store the entered value using stdin.readLineSync()!
parse the input into an int using int.parse(input) if necessary
Code:
import 'dart:io';
void main() {
String? string;
var number;
stdout.writeln("Enter a String: ");
string = stdin.readLineSync()!;
stdout.writeln("Enter a number: ");
number = int.parse(stdin.readLineSync()!);
}

Resources