in vs code, i am getting this error in the basic input taking code from the user
my complete code:
import 'dart:io';
void main(){
stdout.write("Enter your name : ");
var name = stdin.readLineSync();
stdout.write(name);
}
Error in the compiler:
playground.dart:9:23: Error: Method not found: 'Stdin.readLineSync'.
String name = Stdin.readLineSync();
^^^^^^^^^^^^
You must add:
import 'dart:io';
before your main function
To learn dart as console application you should use IntelliJ IDEA IDE.
This is the best IDE for dart.
vscode, dartpad does not support stdin stdout.
if you were getting error like
"Getter not found.'stdin'"
in VSCode check for the extension "dart" is installed on your VSCode then checkitout for run i.e dart run command
stdin.readLineSync()!
use the '!' as I did below:
void main(){
stdout.write("Enter your name : ");
var name = stdin.readLineSync()!;
stdout.write(name);
}
The error you get with stdin.readLineSync() is due to null safety introduced in Dart 2.12. Just add (!)
var name = stdin.readLineSync()!;
you should write it -> stdout.writeln and also import the library for it, I amended the code for you below, and it works fine on VSCode
import 'dart:io';
void main(){
stdout.writeln("Enter your name : ");
var name = stdin.readLineSync();
stdout.write(name);
}
Related
I'm writing a discord bot using the nyxx library and want use dynamic file import for load command info and handler. But, after 5 hours of searching with Google, I didn't find anything to help me do that.
In Node.js, I can use require() or import() for it: Does the dart have something like that?
A small code snippet, showing what I want do:
this.commands = new Collection();
fs.readdirSync('./src/commands').filter(( f ) => f.endsWith( '.js' )).forEach((file) => {
const command = require(`../commands/${file}`);
this.commands.set( command.info.name, command );
});
Is it possible to do this or not? (I don't like to write many imports for commands and register it in lib.)
You can in theory use Isolate.spawnUri to spawn external Dart programs to run in its own Isolate instances that can then communicate back to the main program using SendPort.
It does, however, come with some limitations. E.g. it is very limited what types of objects you can send though SendPort when using spawnUri since the two programs does not share any type information (compared to Isolate.spawn which does allow you to send your own custom types). The documented types you can send can be found here:
Null
bool
int
double
String
List or Map (whose elements are any of these)
TransferableTypedData
SendPort
Capability
https://api.dart.dev/stable/2.17.6/dart-isolate/SendPort/send.html
But it does allow us to make some kind of protocol and you can create some helper class around this to handle the conversion of a known object structure into e.g. Map<String, Object>.
A small example that works with Dart VM would be:
Your command implemented as: command.dart
import 'dart:isolate';
void main(List<String> arguments, Map<String, Object> message) {
final userName = message['username'] as String;
final sendPort = message['port'] as SendPort;
sendPort.send('Hi $userName. '
'You got a message from my external command program!');
}
Your server that calls your command: server.dart
import 'dart:isolate';
void main() {
final recievePort = ReceivePort();
recievePort.listen((message) {
print('Got the following message: $message');
recievePort.close();
});
Isolate.spawnUri(Uri.file('command.dart'), [], {
'username': 'julemand101',
'port': recievePort.sendPort,
});
}
If running this with: dart server.dart you, hopefully, get:
Got the following message: Hi julemand101. You got a message from my external command program!
If you want to compile your application, you can do so by doing the following. You need to compile the command.dart, since a compiled Dart program does not understand how to read Dart code.
dart compile exe server.dart
dart compile aot-snapshot command.dart
You should here change Uri.file('command.dart') to Uri.file('command.aot') since the file-extension for aot-snapshot are .aot.
If everything works, you should be able to see:
> .\server.exe
Got the following message: Hi julemand101. You got a message from my external command program!
I'm unable to get input values entered using console. Whenever I'm using readLineSync() function, it results in an error saying "Global Evaluation not Supported".
I've been trying finding another function to do the same but left with only readLineSync().
import 'dart:io';
void main() {
print("What's your name?");
var name = stdin.readLineSync();
print("Welcome back user: $name");
}
Current Dart environment:
Dart VM version: 2.0.0-dev.69.0 (Unknown timestamp) on "linux_x64"
I am attempting to spawn an isolate via the Isolate.spawnUri method, and include a SendPort within the message. The code I have is set up like:
import 'dart:convert' show json;
import 'dart:isolate';
var servicePort = new ReceivePort()
..listen (/stuff to handle response/);
Map isolateRequest = {
'sendPort': servicePort.sendPort, <-- String => SendPort
'info': json.encode (/info to send to spawned isolate/) <-- String => String
};
Isolate.spawnUri (new Uri.file (/isolate main/), [], isolateRequest);
This type of set up used to work. Now I get the following error:
"Invalid argument(s): Illegal argument in isolate message : (object is a regular Dart Instance)"
The two keys for the Map are strings, and the values include a SendPort and another string. Simple, nothing fancy, and should be acceptable to send as the message to spawn the isolate (worked perfectly up until a few days ago).
Questions: what changed that I am now doing something wrong? What are potential workarounds?
Any help will be greatly appreciated.
This does not reproduce for me with a freshly build VM from the 2.0.0-dev.69.0 tag (--version is: Dart VM version: 2.0.0-dev.69.0 (Tue Jul 17 14:57:16 2018 +0200) on "linux_x64").
Using this complete program:
import 'dart:convert' show json;
import 'dart:isolate';
main(args, message) {
if (message != null) {
print("Out, ");
message["sendPort"].send("And home again!");
return;
}
var servicePort = new ReceivePort();
servicePort.forEach((m) {
print(m);
servicePort.close();
});
Map isolateRequest = {
'sendPort': servicePort.sendPort, // <-- String => SendPort
'info': json.encode({}) // <-- String => String
};
Isolate.spawnUri (new Uri(path:"iso.dart"), [], isolateRequest);
}
it runs and prints the expected lines.
The isolate request does look like something that should be serializable (map with string keys and values that are either strings or a SendPort), something else must be going on in the code you are not showing.
Can you extract a runnable program from your code which still exhibits this behavior, or say something more about what happens around the code?
I'm attempting to re-write some Go code in C mainly as a learning experience, however I have ran into an issue to which I cannot find the answer to elsewhere.
I am attempting to run the following code:
package conv
/*
#include <stdio.h>
int** ConvertStringToArray(char* str){
printf("%s\n", str);
}
*/
import (
"C"
"unsafe"
)
func ToArrayGo(str string) [][]int {
return nil // TODO
}
func ToArrayC(str string) [][]int {
C.ConvertStringToArray(C.CString(str))
return nil // TODO
}
If I comment out the unsafe import it works just fine, however when I add it in I get the following error with the go install/test commands:
37: error: 'ConvertStringToArray' undeclared (first use in this function)
This is also the case whenever I try to import any other libraries. Any help would be appreciated or even a redirect to a relevant issue (I've already looked but may have missed one).
Thanks,
Dave
import "C"
should be a line unto itself, and the first import. Then you can
import (
"unsafe"
)
as the next line.
I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;
unable to resolve class com.jidesoft.swing.JideSplitButton
from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
I even tried running the grape command line tool to ensure the library is imported. Like this;
$ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss
which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?
There is still some kinks in working out the startup/kill switch routine. For Beta-2 do this in it's own script first:
groovy.grape.Grape.initGrape()
Another issue you will run into deals with the joys of using an unbounded upper range. Jide-oss from 2.3.0 onward has been compiling their code to Java 6 bytecodes, so you will need to either run the console in Java 6 (which is what you would want to do for Swing anyway) or set an upper limit on the ranges, like so
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
new TestClassAnnotation().testMethod()
I finally got it working for Groovy Shell (1.6.5, JVM: 1.6.0_13). This should be documented better.
First at the command line...
grape install org.codehaus.groovy.modules.http-builder http-builder 0.5.0-RC2
Then in groovysh...
groovy:000> import groovy.grape.Grape
groovy:000> Grape.grab(group:'org.codehaus.groovy.modules.http-builder', module:'http-builder', version:'0.5.0-RC2')
groovy:000> def http= new groovyx.net.http.HTTPBuilder('http://rovio')
===> groovyx.net.http.HTTPBuilder#91520
The #grab is better used in a file than the shell.
Ok. Seems like this a short working demo (running from the groovyConsole)
groovy.grape.Grape.initGrape()
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class UsedToExposeAnnotationToComplier {}
com.jidesoft.swing.JideSplitButton.class.name
When run it produces
Result: "com.jidesoft.swing.JideSplitButton"
Very cool!!
The import statement must appear after the grabs.
Ps. At least one import statement must exists after the grabs
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
import com.jidesoft.swing.JideSplitButton
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
Different example using latest RC-2 (note: Grab annotates createEmptyInts):
// create and use a primitive array
import org.apache.commons.collections.primitives.ArrayIntList
#Grab(group='commons-primitives', module='commons-primitives', version='1.0')
def createEmptyInts() { new ArrayIntList() }
def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42
Another example (note: Grab annotates getHtml):
// find the PDF links in the Java 1.5.0 documentation
#Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def getHtml() {
def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
parser.parse("http://java.sun.com/j2se/1.5.0/download-pdf.html")
}
html.body.'**'.a.#href.grep(~/.*\.pdf/).each{ println it }
Another example (note: Grab annotates getFruit):
// Google Collections example
import com.google.common.collect.HashBiMap
#Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')
def getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }
assert fruit.inverse().yellow == 'lemon'