Home Programming Dart Cookbook

Dart Cookbook

By Ivo Balbaert
books-svg-icon Book
eBook $28.99
Print $48.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99
Print $48.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Working with Dart Tools
About this book
Publication date:
October 2014
Publisher
Packt
Pages
346
ISBN
9781783989621

 

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:

    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:mypassword@127.0.0.1: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.

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

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.

About the Author
  • Ivo Balbaert

    Ivo Balbaert is a lecturer in web programming and databases at CVO Antwerpen, a community college in Belgium. He received a PhD in applied physics from the University of Antwerp in 1986. He worked for 20 years in the software industry as a developer and consultant in several companies, and for 10 years as project manager at the University Hospital of Antwerp. From 2000 onwards, he switched to partly teaching and partly developing software (at KHM Mechelen, CVO Antwerpen). He also wrote an introductory book in Dutch about developing in Ruby and Rails, Programmeren met Ruby en Rails, published by Van Duuren Media. In 2012, he authored a book on the Go programming language, The Way to Go, published by iUniverse. He has written a number of introductory books for new programming languages, notably Dart, Julia, Rust, and Red, all published by Packt.

    Browse publications by this author
Latest Reviews (1 reviews total)
This book is also too good ! It has some really interesting and original solutions ....
Dart Cookbook
Unlock this book and the full library FREE for 7 days
Start now