Recently I was trying out some code snippets from "Dart For Absolute Beginners" on DartPad.
Specifically:
import 'dart:math';
import 'dart:io';
void main()
{
int guess;
Random rand = new Random(); //create a random number generator
int answer = rand.nextInt(100); //gets a random integer from 0 to 99
do
{
print("Enter your guess:");
String temp = stdin.readLineSync(); //read in from the keyboard
guess = int.parse(temp); //convert String to integer
if (guess < answer)
{
print("Too low!");
}
else if (guess > answer)
{
print("Too high!");
}
}
while (guess != answer);
print("You got it!");
}
However upon running, it shows the error "Error compiling to JavaScript:
unsupported import: dart:io"
So my question is
Is it that we can't run I/O operations on DartPad and we need a full fledge editor for that ?
or is there something else wrong ??
The dart:io library is not supported in DartPad. However you can use this Dart compiler, it supports dart:io.
As noted in the dart:io documentation:
Important: Browser-based apps can't use this library. Only the following can import and use the dart:io library:
Servers
Command-line scripts
Flutter mobile apps
Flutter desktop apps
Related
how can i auto press enter key in dart language for windows platform applications?
Honestly, I couldn't find clear information on this subject.
c# usage:
SendKeys.Send("{ENTER}");
Use the win32 package. The sendInput method is documented here: https://pub.dev/documentation/win32/latest/win32/SendInput.html and https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput
Typical usage:
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';
void main() {
final pInputs = calloc<INPUT>(); // allocate an empty input struct
pInputs.ref.type = INPUT_KEYBOARD; // set the type to keyboard
pInputs.ref.ki.wVk = VK_RETURN; // set the value to return key
// see the example at https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput#example
// for useful ideas
final rc = SendInput(1, pInputs, sizeOf<INPUT>()); // send the input
calloc.free(pInputs); // free the allocated memory
}
I wonder if there is a way to #define short_expression long_expression in Dart/Flutter?
For example, instead of typing
MediaQuery.of(context).size.width
// or
Locale.of(context).translate("x")
in every build function, we can
#define MQWidth MediaQuery.of(context).size.width
// or
#define Lt(x) Locale.of(context).translate("x")
then use it in every build function instead?
Macros. Generative programming aka metaprogramming is usually not a thing in interpreted languages. The closest thing to generative programming concept in dart would be static metaprogramming that is actively being chased by. You can currently achieve source code generation in dart via build_runner, which I believe you have seen for example in packages such as json_serializable, and retrofit. But it's still way too far from perfect and requires a lot of work to achieve something even minuscule. And it only fits into certain scenarios and the example you gave is sadly not one of them.
So, the answer is no. You can't do that, at least as of now.
But instead why don't you just separate that into functions if they are really overused all over the place. I know you still have to pass in the context everywhere which is kinda cluttering compared to what you have expected. But it'll still make the code much shorter, if that's your goal.
Hope this answers your question. Cheers!
An example of how this can be done.
By the way, this is the simplest example. Without using of the macro arguments (AST nodes).
Input: bin/main.dart
#pragma('meta_expression:build')
library my_cool_library;
#pragma('meta_expression:import')
import 'package:test_meta_expression/my_cool_macros.dart';
void main(List<String> args) {
final a = mqWidth();
final b = lt('Hello!');
print(a);
print(b);
}
Output: bin/main.impl.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// MetaExpressionLibraryGenerator
// **************************************************************************
library my_cool_library;
void main(List<String> args) {
//
final a = MediaQuery.of(context).size.width;
final b = Locale.of(context).translate('Hello!');
print(a);
print(b);
}
Macro: package:test_meta_expression/my_cool_macros.dart
import 'package:meta_expression_annotation/meta_expression_annotation.dart';
#MetaExpression(mqWidthImpl)
external int mqWidth();
String mqWidthImpl(MetaContext context) => '''
MediaQuery.of(context).size.width
''';
#MetaExpression(ltImpl)
external String lt(String x);
String ltImpl(MetaContext context) => '''
Locale.of(context).translate(x)
''';
File: pubspec.yaml
dependencies:
meta_expression_annotation: 0.2.1
dev_dependencies:
build_runner: any
meta_expression: 0.2.1
Build command:
dart run build_runner build
I am using VS Code.
Supposedly there is a function called inspect() in dart that allows you to vardump an object.
my barebones example is as follows:
import 'dart:developer';
class User {
String name;
int age;
User(this.name, this.age);
}
void main() {
User newUser = User("Steve", 30);
inspect(newUser);
print('done');
}
I don't get any errors, but all I see in the Debug Console is "done"
On this page there is am image showing inspect() sample output (4th image from the top) in the Debug Console:
Link
Is there something else I need to do to make this command work in VS Code?
I try to use the same code for both web and android. Where the code differs I switch between widgets based on a global variable.
Is the performance worse when using a non constant / non final variable when switching between widgets? I'm thinking, because the variable is not final or constant and can be changed at any point, Flutter will not be able to optimise the code. Is that true? If inefficient, how do I make my code efficient?
eg.
I have two main files and set my AppType enum in each
[appType.dart]
AppType appType; //can't think of how to make this constant or final
[android_main.dart]
void main() {
appType = AppType.and;
[web_main.dart]
void main() {
appType = AppType.and;
In my widgets I switch where I need a widget specific for the web or android
if(appType == AppType.web)
return MyWidgetWeb();
else
return MyWeigetAnd();
Yes, a constant is more efficient, mainly because of tree-shaking.
Assume that you have the following types:
enum AppType {
mobile,
web,
}
class Mobile {}
class Web {}
Then when you write:
const type = AppType.web;
void main() {
if (type == AppType.web) {
print(Web());
}
else if (type == AppType.mobile) {
print(Mobile());
}
}
Then when compiling the code, the compiler knows that the if block will always be reached, and the else if never will.
As such:
the conditions are removed. When compiled, the code will be:
const type = AppType.web;
void main() {
// no `if` performed
print(Web());
}
Mobile will not be bundled in the executable, so you have a lighter application.
To fully benefit from this behavior, you can use Dart "defines", using int/bool/String.fromEnvironment, which allows you to define constants that behave differently depending on some external build parameters.
The way such constant would look like is:
const isWeb = bool.fromEnvironment('isWeb', defaultValue: false);
Which you can then control using arguments on flutter run and flutter build commands:
flutter build <whatever> --dart-define=isWeb=true
I'm running a flutter application in VSCode and want to print to console using this code:
stdout.write('Text');
But the console doesn't show anything after executing this line. Why is that?
(print statements work as expected).
EDIT:
the print function works fine. I just wanted to print something inside a for loop without a newline, that's why I was trying to use stdout.writeln. I ended up building the string I wanted to print in the for loop and printing it only once with the print function.
I had the same problem, "solved" it using StringBuffer and one final print:
final StringBuffer buffer = StringBuffer();
for (var i = 0; i < 100; i++) {
buffer.write('$i, ');
}
print(buffer.toString());
Just use print("Hello console"); =D
I had the same problem myself.
Unfortunately I can't tell you the reason why stdout doesn't work on terminal logs but I can tell you that you can see them using Dart DevTools on the part of Logging
Same here. In my case this code
import 'dart:io';
void main() {
for (int i = 0; i <= 10; i = i + 2) {
stdout.write('$i ');
}
}
Do not show this output in VS Code console.
0 2 4 8 10
It does in other IDEs so I guess it's VS Code problem.