In this chapter, we will cover the following recipes:
Configuring the Dart environment
Setting up the checked and production modes
Rapid Dart Editor troubleshooting
Hosting your own private pub mirror
Using Sublime Text 2 as an IDE
Compiling your app to JavaScript
Debugging your app in JavaScript for Chrome
Using the command-line tools
Solving problems when pub get fails
Shrinking the size of your app
Making a system call
Using snapshotting
Getting information from the operating system
This chapter is about increasing our mastery of the Dart platform. Dart is Google's new language for the modern web, web clients, as well as server applications. Compared to JavaScript, Dart is a higher-level language so it will yield better productivity. Moreover, it delivers increased performance. To tame all that power, we need a good working environment, which is precisely what Dart Editor provides. Dart Editor is quite a comprehensive environment in its own right and it is worthwhile to know the more advanced and hidden features it exposes. Some functionalities are only available in the command-line tools, so we must discuss these as well.
This recipe will help customize the Dart environment according to our requirements. Here, we configure the following:
Defining a
DART_SDK
environment variableMaking
dart-sdk\bin
available for the execution of the Dart command-line tools
We assume that you have a working Dart environment installed on your machine. If not, go to https://www.dartlang.org/tools/download.html and choose Option 1 for your platform, which is the complete bundle. Downloading and uncompressing it will produce a folder named dart
, which will contain everything you need. Put this in a directory of your choice. This could be anything, but for convenience keep it short, such as d:\dart
on Windows or ~/dart
on Linux. On OS X, you can just drop the directory in the App
folder.
Create a
DART_SDK
environment variable that contains the path to thedart-sdk
folder. On Windows, create and setDART_SDK
tod:\dart\dart-sdk
or<your-dart-sdk-path>\dart-sdk
when using a dart from another folder (if you need more information on how to do this, refer to http://www.c-sharpcorner.com/UploadFile/6cde20/use-of-environment-variable-in-windows-8/). On Linux, add this to your configuration file.bashrc
and/or.profile
using theexport DART_SDK=~/dart/dart-sdk
code. On OS X, exportDART_SDK=/Applications/dart/dart-sdk
or in general exportDART_SDK=/path/to/dart-sdk
.The installation directory has a subfolder
dart-sdk\bin
, which contains the command-line tools. Add this subfolder to the path of your environment. On Windows, add%DART_SDK%\bin
instead to the front of the path (system environment) variable and click on OK. On Linux or OS X, addexport PATH=$PATH:$DART_SDK/bin
to your configuration file.Reset your environment configuration file or reboot your machine afterwards for the changes to take effect.
Setting the DART_SDK
environment variable, for example, enables plugins such as dart-maven to search for the Dart SDK (dart-maven is a plugin that provides integration for Google Dart into a maven-build process). If the OS of your machine knows the path where the Dart tools reside, you can start any of them (such as the Dart VM or dartanalyzer) anywhere in a terminal or command-line session.
Test the environment variable by typing dart
in a terminal and press Enter. You should see the following help text:
Usage: dart [<vm-flags>] <dart-script-file> [<dart-options>]
Executes the Dart script passed as <dart-script-file>
When developing or maintaining, an app's execution speed is not so important, but information about the program's execution is. On the other hand, when the app is put in a customer environment to run, the requirements are nearly the opposite; speed is of utmost importance, and the less information the program reveals about itself, the better. That's why when an app runs in the Dart Virtual Machine (VM), it can do so in two runtime modes:
The Checked mode: This is also known as the debug mode. The checked mode is used during development and gives you warnings and errors of possible bugs in the code.
The Production mode: This is also known as the release mode. You deploy an app in the production mode when you want it to run as fast as possible, unhindered by code checks.
Open your app in Dart Editor and select the startup web page or Dart script, usually web\index.html
.
When working in Dart Editor, the checked mode is the default mode. If you want the production mode, open the Run menu and select Manage Launches (Ctrl + Shift + M). The Manage Launches window appears, as shown in the following screenshot:
The Manage Launches window
Under Dartium settings, you will see the checkbox Run in checked mode. (If you have selected a Dart script, it will be under the header VM settings.) Uncheck this to run the script in the production mode. Next, click on Apply and then on Close, or on Run immediately. This setting will remain in place until you change it again.
Scripts that are started on the command line (or in a batch file) with the dart
command run in the Dart VM and thus in the production mode. If you want to run the Dart VM in the checked mode, you have to explicitly state that with the following command:
dart –c script.dart or: dart --checked script.dart
You can start Dartium (this is Chromium with the Dart VM) directly by launching the Chrome executable from dart\chromium
; by default, it runs Dart Editor in the production mode. If you would like to start Dartium in the checked mode, you can do this as follows:
On Windows, in the
dart\chromium
folder, click on thechrome
fileOn Linux, in the
~/dart/chromium
folder, open the./chrome
fileOn OS X, open the
DART_FLAGS
folder and then openpath/Chromium.app
Verify this setting by going to the following address in the Chrome browser that you just started chromium://version
.
When a web app runs in the Dart VM in Chrome, it will run in the production mode, by default.
In the checked mode, types are checked by calling assertions of the form assert
(var1 is T)
to make sure that var1
is of type T
. This happens whenever you perform assignments, pass parameters to a function, or return results from a function.
However, Dart is a dynamic language where types are optional. That's why the VM must, in the production mode, execute your code as if the type
annotations (such as int n
) do not exist; they are effectively thrown away. So at runtime, the following statement int x = 1
is equivalent to var x = 1
.
With the checked mode, Dart helps you catch type errors during development. This is in contrast to the other dynamic languages, such as Python, Ruby, and JavaScript, where these are only caught during testing, or much worse, they provoke runtime exceptions. You can easily check whether your Dart app runs in the checked mode or not by calling the function isCheckedMode()
from main()
(see the script test_checked_mode\bin\ test_checked_mode.dart
in the Chapter 1
folder of the code bundle), as shown in the following code:
main() { isCheckedMode(); // your code starts here } void isCheckedMode() { try { int n = ''; throw new Exception("Checked Mode is disabled!"); } on TypeError { print("Checked Mode is enabled!"); } }
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
The exception message will be shown in the browser console. Be sure to remove this call or comment it out before deploying it to the production mode; we don't want an exception at runtime!
Dart Editor is based upon the Eclipse Integrated Development Environment (IDE), so it needs the Java VM to run. Sometimes, problems can arise because of this; if this is the case, be sure to consult the Dart Editor Troubleshooting page on the Dart website at https://www.dartlang.org/tools/editor/troubleshoot.html.
Some of the JVM settings used by Dart Editor are stored in the DartEditor.ini
file in the dart
installation directory. This typically contains the following settings (on a Windows system):
-data @user.home\DartEditor -vmargs -d64 -Dosgi.requiredJavaVersion=1.6 -Dfile.encoding=UTF-8 -XX:MaxPermSize=128m -Xms256m -Xmx2000m
If you notice strange or unwanted behavior in the editor, deleting the settings
folder pointed to by –data
and its subfolders can restore things to normal. This folder can be found at different locations depending on the OS; the locations are as follows:
On a Windows system,
C:\Users\{your username}\DartEditor
On a Linux system,
$HOME/.dartEditor
On an OS X system,
$HOME/Library/Application Support/DartEditor
Deleting the settings folder doesn't harm your system because a new settings folder is created as soon as you reopen Dart Editor. You will have to reload your projects though. If you want to save the old settings, you can rename the folder instead of just deleting it; this way, you can revert to the old settings if you ever want to.
The settings for data points to the DartEditor
folder are in the users home directory, which contains various settings (the metadata) for the editor. Clearing all the settings removes the metadata the editor uses.
The -d64 or –d32 value specifies the bit width necessary for the JVM. You can check these settings for your installation by issuing the command java –version
in a terminal session, whose output will be as follows:
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
If this does not correspond with the –d
setting, make sure that your downloaded Dart Editor and the installed JVM have the same bit width, by downloading a JVM for your bit width.
Tip
If you work with many Dart projects and/or large files, the memory consumption of the JVM will grow accordingly and your editor will become very slow and unresponsive.
Working within a 32-bit environment will pretty much limit you to 1GB memory consumption, so if you see this behavior, it is recommended to switch to a 64-bit system (Dart Editor and JVM). You can then also set the value of the –Xmx
parameter (which is by default set to 2000m = 2 GB) to a higher setting, according to the amount of memory you have installed. This will visibly improve the loading and working speed of your editor!
If your JVM is not installed in the default location, you can add the following line to the .ini
file in the line before -vmargs
:
-vm /full/path/to/java
If you face a problem, it might be solved by upgrading Dart SDK and the Dart Editor to the latest version. In the Dart Editor menu, select Help and then About Dart Editor. If a new version is available, this will automatically download, and when done, click on Apply the update.
Another possibility for when the pub repository is not reachable (because you have no Internet access or work behind a very strict firewall) is to host your own private pub mirror.
Follow these steps to host your own private pub mirror:
You need a server that speaks to the pub's HTTP API. Documentation on that standalone API does not yet exist, but the main pub server running at pub.dartlang.org is open source with its code living at https://github.com/dart-lang/pub-dartlang. To run the server locally, go through these steps:
Install the App Engine SDK for Python.
Verify that its path is in
$PATH
.Install the pip installation file, beautifulsoup4, and pycrypto webtest packages.
From the top-level directory, run this command to start the pub server
dev_appserver.py app
.Verify that it works in your browser with
http://localhost:8080/
.
You need to set a
PUB_HOSTED_URL
environment variable to point to the URL of your mirror server, so that the pub will look there to download the hosted dependencies, for example,PUB_HOSTED_URL = http://me:mypassword@127.0.0.1:8042
.Manually upload the packages you need to your server, visit
http://localhost:8080/admin
(sign in as an administrator), go to the Private Key tab, and enter any string into the private key field.
The server from https://pub.dartlang.org/ is written in Python and is made to run on Google App Engine, but it can be run from an Intranet as well.
Dart Editor is a great environment, but Sublime Text also has many functionalities and can be used with many other languages, making it the preferred editor for many developers.
You can download Sublime Text free of cost for evaluation, however, for continued use, a license must be purchased from http://www.sublimetext.com/.
Tim Armstrong from Google developed a Dart plugin for Sublime Text, which can be downloaded from GitHub at https://github.com/dart-lang/dart-sublime-bundle, or you can find it in the code download with this book. The easiest way to get started is to install the Package Control plugin first by following the instructions at https://sublime.wbond.net/installation#st2.
In Sublime Text, press Ctrl + Shi ft + P (Windows or Linux) or Cmd + Shift + P (OS X; this goes for all the following commands), click on Install Package to choose that option, and then click and choose Dart to install the plugin. Any Dart file you then open shows the highlighted syntax, matching brackets, and so on.
Also, click on Menu Preferences, Settings, and then on User and add the path to your dart-sdk as the first line in this JSON file:
{ "dartsdk_path": "path\to\dart-sdk", … }
If you want to manually install this plugin, copy the contents of the dart-sublime-bundle-master
folder to a new directory named Dart
in the Sublime packages
directory. This directory has different locations on different OS. They are as follows:
On Windows, this will likely be found at
C:\Users\{your username}\AppData\Roaming\Sublime Text 2\Packages
On Linux, this will likely be found at
$HOME/Sublime Text 2/Pristine Packages
On OSX, this will likely be found at
~/Library/Application Support/Sublime Text 2/Packages
The plugin has a number of code snippets to facilitate working with Dart, for example, typing lib
expands the library statement. Other snippets include imp
for import, class
for a class template, method
for a method template, and main
for a main()
function. Typing a snippet in the pop-up window after pressing Ctrl + SHIFT + P lets you see a list of all the snippets. Use Ctrl + / to (un)comment the selected code text.
The plugin has also made a build system for you. Ctrl + B will invoke the dartanalyzer and then compile the Dart code to JavaScript with the dart2js compiler, as shown in the following screenshot. Editing and saving a pubspec.yaml
file will automatically invoke the pub get
command.

Working in Sublime Text 2
Deploying a Dart app in a browser means running it in a JavaScript engine, so the Dart code has to first be compiled to JavaScript. This is done through the dart2js
tool, which is itself written in Dart and lives in the bin
subfolder of dart-sdk
. The tool is also nicely integrated in Dart Editor.
Right-click on
.html
or the.dart
file and select Run as JavaScript.Alternatively, you can right-click on the
pubspec.yaml
file and select Pub Build (generates JS) from the context menu. You can also click on the Tools menu while selecting the same file, and then on Pub Build.
The first option invokes the pub serve
command to start a local web server invoking dart2js along its way in the checked mode. However, the compiled .dart.js
file is served from the memory by the internal development web server on http://127.0.0.1:4031
. This is only good for development testing.
In the second option, the generated files are written to disk in a subfolder build/web
of your app. In this way, you can copy this folder to a production web server and deploy your web app to run in all the modern web browsers (you only need to deploy the .js
file, not the .precompiled.js
file or the .map
file). However, Pub Build in Dart Editor enables the checked mode by default; use the pub build
command from a console for the production mode.
The dart2js
file can also be run from the command line, which is the preferred way to build non-web apps.
Tip
The command to compile the dart script to an output file prorabbits.js
using -o <file>
or -out <file>
is dart2js -o prorabbits.js prorabbits.dart
.
If you want to enable the checked mode in the JavaScript version, use the –c
or - checked
option such as dart2js –c -o prorabbits.js prorabbits.dart
. The command dart2js –vh
gives a detailed overview of all the options.
The pub build
command, issued on a command line in the folder where pubspec.yaml
is located, will do the same as in option 2 previously, but also apply the JavaScript shrinking step; the following is an example output for app test_pub
:
f:\code\test_pub>pub build
Loading source assets... (0.7s)
Building test_pub... (0.3s)
[Info from Dart2JS]:
Compiling test_pub|web/test.dart...
[Info from Dart2JS]: Took 0:00:01.770028 to compile test_pub|web/test.dart. Built 165 files to "build"
You can minify both the JavaScript version and the Dart version of your app.
To produce more readable JavaScript code (instead of the minified version of the production mode, refer to the Shrinking the size of your app recipe), use the command pub build --mode=debug
, which is the default command in Dart Editor.
Alternatively, you can add the following transformers section to your app's pubspec.yaml
file:
name: test_pub description: testing pub transformers: - $dart2js: minify: false checked: true dependencies: js: any dev_dependencies: unittest: any
Note
For more information, refer to https://www.dartlang.org/tools/pub/dart2js-transformer.html.
The dart2js
tool can also be used as Dart to Dart to create a single .dart
file that contains everything you need for the app with this command:
dart2js --output-type=dart --minify -oapp.complete.dart app.dart
This takes the Dart app, tree shakes it, minifies it, and generates a single .dart
file to deploy. The advantage is that it pulls in dependencies like third-party libraries and tree shakes it to eliminate the unused parts.
In this recipe, we will examine how to debug your app in the Chrome browser.
From the menu in the upper right-hand corner, select Tools and then Developer Tools.
Verify via Settings (which is the wheel icon in the upper right corner of the Developer Tools section) that the Enable JavaScript source maps option is turned on. Make sure that debugging is enabled, either on all the exceptions or only on uncaught exceptions.
Choose Sources in the Developer Tools menu, then press Ctrl + O to open a file browser and select the Dart script you wish to debug.
Now reload the application and you will see that the execution stops at the breakpoint. On the right, you have a debug menu, which allows you to inspect scope variables, watch the call stack, and even create watch expressions, as shown in the following screenshot:
Debugging JS in Chrome
Chrome uses the source map file <file>.js.map
generated while compiling the JavaScript code to map the Dart code to the JavaScript code in order to be able to debug it.
In this recipe, we will examine how to debug your app in the Firefox browser.
In Firefox, the source maps feature is not yet implemented. Use Shift + F2 to get the developer toolbar and the command line. In the top menu, you will see Debugger. Place a breakpoint and reload the file. Code execution then stops and you can inspect the value of the variables, as shown in the following screenshot:

Debugging JS in Firefox
Some things can be done more easily on the command-line, or are simply not (yet) included in Dart Editor. These tools are found in dart-sdk/bin
. They consist of the following:
For every tool, it might be useful to know or check its version. This is done with the
-- version
option such asdart --version
with a typical output of Dart VM version: 1.3.0 (Tue Apr 08 09:06:23 2014) on "windows_ia32".The
dart –v –h
option lists and discusses all the possible options of the VM. Many tools also take the--package_root=<path>
or–p=<path>
option to indicate where the packages used in the imports reside on the filesystem.dartanalyzer is written in Java and works in Dart Editor whenever a project is imported or Dart code is changed; it is started
dartanalyzer prorabbits.dart
with output:Analyzing prorabbits.dart...
No issues found (or possibly errors and hints to improve the code)
The previous output verifies that the code conforms to the language specification https://www.dartlang.org/docs/spec/, pub functionality is built into Dart Editor, but the tool can also be used from the command line (refer to
test_pub
). To fetch packages (for example, for thetest_pub
app), use the following command in the folder wherepubspec.yaml
lives,pub get
, with a typical output as follows:Resolving dependencies... (6.6s) Got dependencies!
A packages folder is created with symlinks to the central
package
cache on your machine. The latest versions are downloaded and the package versions are registered in thepubspec.lock
file, so that your app can only use these versions.If you want to get a newer version of a package, use the
pub upgrade
command. You can use the–v
and-- trace
options to produce a detailed output to verify its workings.The
dartfmt
tool is also a built in Dart Editor. Right-click on any Dart file and choose Format from the context menu. This applies transformations to the code so that it conforms to the Dart Style Guide, which can be seen at https://www.dartlang.org/articles/style-guide/.You can also use it from the command line, but then the default operation mode is cleaning up whitespace. Use the–t
option to apply code transforms such asdartfmt -t –w bank_terminal.dart
.
Solving problems when
pub get
failsCompiling your app to JavaScript (for
pub build
)Documenting your code from Chapter 2, Structuring, testing, and deploying an application
Publishing your app to a pub (for pub publishing)
Using snapshotting to start an app in Dart VM
For additional information, refer to https://www.dartlang.org/tools/
The pub package manager is a complex tool with many functionalities, so it is not surprising that occasionally something goes wrong. The pub get
command downloads all the libraries needed by your app, as specified in the pubspec.yaml
file. Running pub get
behind a proxy or firewall used to be a problem, but it was solved in the majority of cases. If this still haunts you, look at the corresponding section at https://www.dartlang.org/tools/editor/troubleshoot.html.
This recipe is especially useful when you encounter the following error in your Dart console while trying to open a project in Dart Editor during the pub get phase:
Pub install fails with 'Deletion failed'
First try this; right-click on your project and select Close Folder. Then, restart the editor and open your project again. In many cases, your project will load fine. If this does not work, try the pub
gun
command:
Delete the pub cache folder from
C:\Users\{your username}\AppData\Roaming\Pub
.Delete all the
packages
folders in your project (also in subfolders).Delete the
pubspec.lock
file in your project.Run
pub get
again from a command line or select Tools in the Dart Editor menu, and then select Pub Get.
The Pub\Cache
subfolder contains all the packages that have been downloaded in your Dart environment. Your project contains symlinks to the projects in this cache, which sometimes go wrong, mostly on Windows. The pubspeck.lock
file keeps the downloaded projects constrained to certain versions; removing this constraint can also be helpful.
Temporarily disabling the virus checker on your system can also help pub get
to succeed when it fails with the virus checker on.
The following script by Richard Schmidt that downloads packages from the pub repository and unpacks it into your Dart cache may also prove to be helpful for this error, which can be found at https://github.com/hangstrap/downloadFromPub. Use it as dart downloadFromPub.dart package m.n.l
.
Here, package
is the package you want to install and m.n.l
is the version number such as 0.8.1. You will need to build this like any other dart package, and if during this process the pub get
command fails, you will have to download the package and unpack it manually; however, from then on, you should be able to use this script to work around this issue.
When pub get
fails in Dart Editor, try the following on the command line to get more information on the possible reasons for the pub --trace 'upgrade'
failure.
There is now also a way to condense these four steps into one command in a terminal as follows:
pub cache repair
On the web, the size of the JavaScript version of your app matters. For this reason, dart2js
is optimized to produce the smallest possible JavaScript files.
When you're ready to deploy, minify the size of the generated JavaScript with –m
or -- minify
, as shown in the following command:
dart2js –m -o prorabbits.js prorabbits.dart
Using pub build
on the command line minifies JavaScript by default because this command is meant for deployment.
The dart2js
file utilizes a tree-shaking feature; only code that is necessary during execution is retained, that is, functions, classes, and libraries that are not called are excluded from the produced .js
file. The minification process further reduces the size by replacing the names of variables, functions, and so on with shorter names and moving code around to use a few lines.
Be careful when you use reflection.
Using reflection in the Dart code prevents tree shaking. So only import the dart:mirrors
library when you really have to. In this case, include an @MirrorsUsed
annotation, as shown in the following code:
library mylib; @MirrorsUsed(targets: 'mylib') import 'dart:mirrors';
In the previous code, all the names and entities (classes, functions, and so on) inside of mylib
will be retained in the generated code to use reflection. So create a separate library to hold the class that is using mirrors.
You might want to consult the Using Reflection recipe in Chapter 4, Object Orientation.
A fairly common use case is that you need to call another program from your Dart app, or an operating system command. For this, the abstract class Process
in the dart:io
package is created.
Use the run
method to begin an external program as shown in the following code snippet, where we start Notepad on a Windows system, which shows the question to open a new file tst.txt
(refer to make_system_call\bin\ make_system_call.dart
):
import 'dart:io'; main() { // running an external program process without interaction: Process.run('notepad', ['tst.txt']).then((ProcessResult rs){ print(rs.exitCode); print(rs.stdout); print(rs.stderr); }); }
If the process is an OS command, use the runInShell
argument, as shown in the following code:
Process.run('dir',[], runInShell:true).then((ProcessResult rs) { … }
The Run
command returns a Future of type ProcessResult
, which you can interrogate for its exit code or any messages. The exit code is OS-specific, but usually a negative value indicates an execution problem.
Use the start
method if your Dart code has to interact with the process by writing to its stdin
stream or listening to its stdout
stream.
One of the advantages of running a Dart app on its own VM is that we can apply snapshotting, thereby reducing the startup time compared to JavaScript. A snapshot is a file with an image of your app in the byte form, containing all the Dart objects as they appear in the heap memory.
To generate a script snapshot file called prorabbits
from the Dart script prorabbits.dart
, issue the following command:
dart --snapshot=prorabbits prorabbits.dart
Then, start the app with dart prorabbits args
, where args
stands for optional arguments needed by the script.
A script snapshot is the byte representation of the app's objects in the memory (more precisely in the heap of the started isolate) after it is loaded, but before it starts executing. This enables a much faster startup because the work of tokenizing and parsing the app's code was already done in the snapshot.
This recipe is intended for server apps or command-line apps. A browser with a built-in Dart VM can snapshot your web app automatically and store that in the browser cache; the next time the app is requested, it starts up way faster from its snapshot. Because a snapshot is in fact a serialized form of an object(s), this is also the way the Dart VM uses to pass objects between isolates. The folder dart/dart-sdk/bin/snapshots
contains snapshots of the main Dart tools.
Occasionally, your app needs access to the operating system, for example, to get the value of an environment variable to know where you are in the filesystem, or to get the number of processors when working with isolates. Refer to the Using isolates in the Dart VM and Using isolates in web apps recipes, in Chapter 8, Working with Futures, Tasks, and Isolates, for more information on working with isolates.
In this recipe, you will see how to interact with the underlying operating system on which your app runs by making system calls and getting information from the system.
The Platform
class provides you with information about the OS and the computer the app is executing on. It lives in dart:io
, so we need to import this library.
The following script shows the use of some interesting options (refer to the code files tools
\code
\platform
\bin
\platform.dart
of this chapter):
import 'dart:io'; Map env = Platform.environment; void main() { print('We run from this VM: ${Platform.executable}'); // getting the OS and Dart version: print('Our OS is: ${Platform.operatingSystem}'); print('We are running Dart version: ${Platform.version}'); if (!Platform.isLinux) { print('We are not running on Linux here!'); } // getting the number of processors: int noProcs = Platform.numberOfProcessors; print('no of processors: $noProcs'); // getting the value of environment variables from the Map env: print('OS = ${env["OS"]}'); print('HOMEDRIVE = ${env["HOMEDRIVE"]}'); print('USERNAME = ${env["USERNAME"]}'); print('PATH = ${env["PATH"]}'); // getting the path to the executing Dart script: var path = Platform.script.path; print('We execute at $path'); // on this OS we use this path separator: print('path separator: ${Platform.pathSeparator}'); }
When run, the above code gives the following output:
Our OS is: windows We are running Dart version: 1.3.3 (Wed Apr 16 12:40:55 2014) on "windows_ia32" We are not running on Linux here! no of processors: 8 OS = Windows_NT HOMEDRIVE = C: USERNAME = CVO PATH = C:\mongodb\bin;C:\MinGW\bin;... We execute at /F:/Dartiverse/platform/bin/platform.dart path separator: \
Most of the options are straightforward. You can get the running VM from Platform.executable
. You can get the OS from Platform.operatingSystem
; this can also be tested on a Boolean property such as Platform.isLinux
. The Dart version can be tested with the Platform.version
property. The Platform.environment
option returns a nice map structure for the environment variables of your system, so you can access their values by name, for example, for a variable envVar
, use var envVar = Platform.environment["envVar"]
.
To get the path of the executing Dart script, you can use the path property of Platform.script
because the latter returns the absolute URI of the script. When building file paths in your app, you need to know how the components in a path are separated; Platform.pathSeparator
gives you this information.