Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
DART Cookbook
DART Cookbook

DART Cookbook: Over 110 incredibly effective, useful, and hands-on recipes to design Dart web client and server applications

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

DART Cookbook

Chapter 1. Working with Dart Tools

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

Introduction

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.

Configuring the Dart environment

This recipe will help customize the Dart environment according to our requirements. Here, we configure the following:

  • Defining a DART_SDK environment variable
  • Making dart-sdk\bin available for the execution of the Dart command-line tools

Getting ready

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.

How to do it...

  1. Create a DART_SDK environment variable that contains the path to the dart-sdk folder. On Windows, create and set DART_SDK to d:\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 the export DART_SDK=~/dart/dart-sdk code. On OS X, export DART_SDK=/Applications/dart/dart-sdk or in general export DART_SDK=/path/to/dart-sdk.
  2. 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, add export PATH=$PATH:$DART_SDK/bin to your configuration file.
  3. Reset your environment configuration file or reboot your machine afterwards for the changes to take effect.

How it works...

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>

Setting up the checked and production modes

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.

Getting ready

Open your app in Dart Editor and select the startup web page or Dart script, usually web\index.html.

How to do it...

  1. 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:
    How to do it...

    The Manage Launches window

  2. 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 the chrome file
  • On Linux, in the ~/dart/chromium folder, open the ./chrome file
  • On OS X, open the DART_FLAGS folder and then open path/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.

How it works...

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.

A binding x is created but the type annotation is not used.

Note

Avoiding type checks makes the production mode a lot faster. Also, the VM uses the type inference to produce faster code; it observes the type of the value (here, 1) assigned to x and optimizes accordingly.

There's more...

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!

See also

  • The Compiling your app to JavaScript recipe of this chapter for how to enable the checked mode in the JavaScript version of the app
  • The Using the command-line tools recipe of this chapter for other options

Rapid Dart Editor troubleshooting

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.

Getting ready

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

Note

The line beneath –data will read @user.home/.dartEditor on a Linux system.

How to do it...

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.

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.

Getting ready

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.

How it works...

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

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.

See also

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 Chrome

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:
    How to do it…

    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 your app in JavaScript for Firefox

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.

See also

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

Getting ready

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.

More Information Section 1

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.

See also

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

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.

See also

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

Getting ready

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:
USERNAME = CVO
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.

Left arrow icon Right arrow icon

Description

If you are a Dart developer looking to sharpen your skills, and get insight and tips on how to put that knowledge into practice, then this book is for you. You should also have a basic knowledge of HTML, and how web applications with browser clients and servers work, in order to build dynamic Dart applications.

What you will learn

  • Set up your Dart environment to achieve the highest productivity
  • Structure, document, test, and deploy your apps
  • Use mixins, reflections, annotations, and other metadata programming techniques to create powerful apps
  • Use the power of modern browsers to process and store data
  • Communicate with JavaScript and use JavaScript libraries
  • Work with files, streams, and web servers by writing asynchronous code
  • Demonstrate the power of Polymer web components for binding data and structuring your web pages
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 24, 2014
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989621
Vendor :
Google
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Oct 24, 2014
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989621
Vendor :
Google
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 128.97
Learning Dart
€49.99
Mastering DART
€41.99
DART Cookbook
€36.99
Total 128.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Working with Dart Tools Chevron down icon Chevron up icon
2. Structuring, Testing, and Deploying an Application Chevron down icon Chevron up icon
3. Working with Data Types Chevron down icon Chevron up icon
4. Object Orientation Chevron down icon Chevron up icon
5. Handling Web Applications Chevron down icon Chevron up icon
6. Working with Files and Streams Chevron down icon Chevron up icon
7. Working with Web Servers Chevron down icon Chevron up icon
8. Working with Futures, Tasks, and Isolates Chevron down icon Chevron up icon
9. Working with Databases Chevron down icon Chevron up icon
10. Polymer Dart Recipes Chevron down icon Chevron up icon
11. Working with Angular Dart Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
Jun Chul Kim Jun 12, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Since tutorials and documents from www.dartlang.org are very good, we can learn Dart without many books. Simple language, common concepts, good articles.I could jumped in within just couple of hours. But, once I jumped in, it was really annoying to find some specific topics from these articles.This cookbook saved lots of my time. Well organized and easy to find topics with concise solutions.Good book for reference just like the other cookbook series.
Amazon Verified review Amazon
W Boudville Jun 13, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The unified aspect of Dart is its raison d'etre, of course, if you have heard of Dart before. One nice aspect of this book is how it gives many recipes for common problems you are likely to meet in the course of learning or applying Dart. Not surprisingly, since Google originated Dart, there are deep connections to the Google Chrome browser. For some of you, that will be another reason to delve into this book carefully.The chapter on Web applications is the best way to see how Dart and Chrome can be integrated easily. More broadly, this and other chapters give links to further documentation online. Where you might get other apps whose source code is accessible; letting you extend them as good learning exercises. Another plus is the use of examples involving WebSockets. The latter let you make web pages that are far more interactive than traditional HTML pages.Experience with data formatted in JSON would help in the web server side discussions. Nothing really hard about this in any event.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela