# Dart Cookbook

5 (1 reviews total)
By Ivo Balbaert
• FREE Subscription Access now

• 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. ### How it works... 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. ### There's more... 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. ## Hosting your own private pub mirror 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. ### How to do it... Follow these steps to host your own private pub mirror: 1. 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: 1. Install the App Engine SDK for Python. 2. Verify that its path is in $PATH.

3. Install the pip installation file, beautifulsoup4, and pycrypto webtest packages.

4. From the top-level directory, run this command to start the pub server dev_appserver.py app.

5. Verify that it works in your browser with http://localhost:8080/.

2. 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:[email protected]:8042.

3. 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.

### How it works...

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.

## Using Sublime Text 2 as an IDE

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.

### How to do it...

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 ### How it works... 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 ### See also • Refer to the Configuring the Dart environment recipe for the path to the Dart SDK ## Compiling your app to JavaScript 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. ### How to do it... • 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. ### How it works... 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. ### There's more... 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. #### Producing more readable JavaScript code 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

#### Producing a single Dart file

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.

You may be interested in the following recipes in this chapter:

• Using the command-line tools

• Shrinking the size of your app

• Debugging your app in JavaScript for Chrom e

## Debugging your app in JavaScript for Chrome

In this recipe, we will examine how to debug your app in the Chrome browser.

### How to do it…

1. From the menu in the upper right-hand corner, select Tools and then Developer Tools.

2. 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.

3. 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.

### Note

Clicking on the left margin before a line of code places a breakpoint, which is indicated by a fat blue arrow.

4. 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

### How it works...

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.

### There's more...

In this recipe, we will examine how to debug your app in the Firefox browser.

#### Debugging your app in JavaScript for Firefox

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

## Using the command-line tools

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:

• dart: The standalone Dart VM to run Dart command-line apps, such as server-side scripts and server apps

• dartanalyzer: This is used to check code statically

• pub: This is the package and repository manager

• dartfmt: This is the code formatting tool

• docgen: This is the documentation generator tool

### How to do it...

1. For every tool, it might be useful to know or check its version. This is done with the -- version option such as dart --version with a typical output of Dart VM version: 1.3.0 (Tue Apr 08 09:06:23 2014) on "windows_ia32".

2. 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.

3. 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)

4. 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 the test_pub app), use the following command in the folder where pubspec.yaml lives, pub get, with a typical output as follows:

Resolving dependencies... (6.6s)
Got dependencies!
5. 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 the pubspec.lock file, so that your app can only use these versions.

6. 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.

### Tip

Always do a pub upgrade if the project you start working on already contains versions of packages!

7. 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 as dartfmt -t –w bank_terminal.dart.

• Solving problems when pub get fails

• Compiling 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/

## Solving problems when pub get fails

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'


### How to do it...

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:

1. Delete the pub cache folder from C:\Users\{your username}\AppData\Roaming\Pub.

2. Delete all the packages folders in your project (also in subfolders).

3. Delete the pubspec.lock file in your project.

4. Run pub get again from a command line or select Tools in the Dart Editor menu, and then select Pub Get.

### How it works...

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.

### There's more...

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


## Shrinking the size of your app

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.

### How to do it...

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.

### How it works...

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.

### There's more...

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.

### Note

Make sure your deployment web server uses gzipping to perform real-time HTTP compression.

• You might want to consult the Using Reflection recipe in Chapter 4, Object Orientation.

## Making a system call

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.

### How to do it...

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:
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)
{ … }

### How it works...

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.

### Note

Both methods work asynchronously; they don't block the main app. If your code has to wait for the process, use runSync.

## Using snapshotting

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.

### How to do it...

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.

### How it works...

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.

### There's more...

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.

## Getting information from the operating system

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.

### How to do it...

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:
PATH = C:\mongodb\bin;C:\MinGW\bin;...
We execute at /F:/Dartiverse/platform/bin/platform.dart
path separator: \

### How it works...

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.

### There's more...

Don't confuse this class with Platform from dart:html, which returns information about the browser platform.