Compiler for dart - 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");
}

Related

How to print console darts? no new lines

I want to display data without adding lines, but I don't want print to increment to the right. instead of editing an existing one,
how to do like docker build result in darts?
You can use
stdout
import 'dart:io';
void main() {
var i = 1;
while (i <= 20) {
stdout.write(i);
stdout.write(' ');
i++;
}
}
I use this simple code to edit the line in the terminal so it doesn't create a new line
import 'dart:io';
void main() {
for (var i = 0; i < 1000; i++) {
stdout.write("\r");
stdout.write("Load: ${i}");
sleep(Duration(milliseconds: 100));
}
print("\nFinished");
}

How do i generate random bytes and convert do hex using dart

I'm trying to generate a Session code based on the following code from PHP in Dart/Flutter:
private $length = 32;
substr(bin2hex(random_bytes($this->length), 0, $this->length);
the problem is that I don't know how to create these random_bytes in dart and then convert them to bin2hex, using DART language.
These functions described above are from PHP (opencart system) which I must to create a hash to specify session from each user connected.
the result expected from this conversion is something like that:
"004959d3386996b8f8b0e6180101059d"
If your goal are just to generate such a hex-string using random numbers, you can do something like this:
import 'dart:math';
void main() {
print(randomHexString(32)); // 1401280aa29717e4940f0845f0d43abd
}
Random _random = Random();
String randomHexString(int length) {
StringBuffer sb = StringBuffer();
for (var i = 0; i < length; i++) {
sb.write(_random.nextInt(16).toRadixString(16));
}
return sb.toString();
}

dart: access function from list

Edit: i know, always call the first element on list, it isnt the point. i want to call numbers[0] func. and it regenerate new int.actually codes are not same which mine, i have a custom class which based on functions with random int and i need to use list of my custom class , so if i use func in list it will be awesome, how can i make new numbers list each time. when app start list regenerated, but i want when i call the list, it will regenerated
i want to print new int for each print but it prints same int , i tried so many thing and i cant figure out
void main{
int ramdomint(){
final _random = new Random();
int _num = _random.nextInt(100);
return _num;
}
List<int> numbers=[ramdomint(),ramdomint(),ramdomint()];
void printNums(){
for(var i=0;i<3;i++){
List<int> newNumbers =new List.from(numbers); //what can i use for this?
print(newNumbers[0]); //edit:i dont want [i], iwant to use ewNumbers[0] for new int for each time
}
}
printNums();
// expected new int for each but same one
}
solution from a friend:
import 'dart:math';
int get ramdomint => Random().nextInt(100);
List<int> get numbers => [ramdomint, ramdomint, ramdomint];
void main() {
for (var i = 0; i < 3; i++) {
print(numbers[0]);
}
}
Do not nest functions. Move ramdomint and printNums outside main function.
Add an empty list of arguments to the main function.
printNums: pass list of numbers as an argument.
printNums: you don't need to copy the list to the newNumbers if you want only to display the content of the list.
printNums: the problem is, you access only first element of the list (with 0 index).
import 'dart:math';
void main() {
List<int> numbers = [ramdomint(), ramdomint(), ramdomint()];
printNums(numbers);
}
int ramdomint() => Random().nextInt(100);
void printNums(List<int> numbers) {
// Easier way:
for (int item in numbers) {
print(item);
}
// Your way:
for (int i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
}
EDIT:
According to #jamesdlin's comment, you can extend list class to randomize unique values in the list:
import 'dart:math';
void main() {
var numbers = <int>[]..randomize();
printNums(numbers);
}
void printNums(List<int> numbers) {
// Easier way:
for (int item in numbers) {
print(item);
}
// Your way:
for (int i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
}
extension on List<int> {
void randomize({
int length = 3,
int maxValue = 100,
}) {
final generator = Random();
for (var i = 0; i < length; i++) {
add(generator.nextInt(maxValue));
}
}
}
The Problem here is that you are creating a list from the numbers list and accessing only the first element.
So it always prints the first element.
import 'dart:math';
void main() {
int ramdomint(){
final _random = new Random();
int _num = _random.nextInt(100);
return _num;
}
List<int> numbers=[ramdomint(),ramdomint(),ramdomint()];
void printNums(){
for(var i=0;i<3;i++){
print(numbers[i]);
}
}
printNums();
}
Don't want newNumbers, because it is already in List.
and the usage of List.from() - Documentation
Hope that works!

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

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());
}

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