I'm using Dart in a Django application. There are configuration parameters that need to be passed to Dart. How do you pass values to main()? At this point I'm considering creating hidden elements in the web page and using query to get the values. Is there a better approach?
3 Answers
Sounds like you are building a browser app?
(BTW, you can use new Options().arguments
for command-line apps. Works great, but obviously there is no command line in browser apps :)
(Second, main()
doesn't take arguments, so we have to find another way.)
OK, for a browser-app, what I might try doing is embedding some JSON into the page inside a <script>
tag. Then, using query, find that element, parse the contents, and you're good to go.
In your HTML:
<script id="config">
{"environment":"test"}
</script>
And in your Dart file:
import 'dart:html';
import 'dart:json' as json;
void main() {
var config = json.parse(query("#config").innerHtml);
print(config['environment']);
}
Hope that helps!

- 71,959
- 15
- 151
- 132

- 112,095
- 66
- 196
- 279
-
Thanks. That's cleaner than what I was thinking of doing. – Alan Humphrey Feb 10 '13 at 07:04
-
This is a fine approach. The other similar approach is to use AJAX/WebSocket to fetch the configuration from the server. The benefit is that you don't need to embed script tags, but the drawback is that it adds latency. I like Seth's approach most. I do also have the habit of *removing* the script tag after using it. – Kai Sellgren Feb 10 '13 at 11:45
Options
is not an option anymore.
Now the main function takes arguments.
main(List<String> args) {
print(args);
}
If you're from python, c, c++. The expectation is that args[0]
will give the script's path.
But in dart args are only the arguments.
To get the script's path Platform.script
can be used which is a Uri
object. Then Uri.path
to get the file path as a String.
An example:
import 'dart:io';
main(List<String> args) {
var dir = Directory.current.path;
var p = Platform.script.path;
print("$p called with $args in $dir");
}

- 4,030
- 3
- 25
- 60
Use the Options as seen in this answer:
#!/usr/bin/env dart
main() {
print("Args: " + new Options().arguments);
}