www.archive-org-2012.com » ORG » D » DARTLANG

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".

    Archived pages: 96 . Archive date: 2012-11.

  • Title: Dart: Structured web apps
    Descriptive info: .. Docs.. Language.. Language Tour.. Language Spec.. Libraries.. Library Tour.. API Reference.. Usage.. Articles.. Tutorials.. FAQ.. Tools.. Editor.. Chromium + Dart VM.. SDK.. Pub Package Manager.. Dart2js.. Dart VM.. Resources.. Code Samples.. Translations from JavaScript.. Presentations.. Books.. Dartisans Videos and Podcast.. Community.. Development.. Bugs and Feature Requests.. Mailing List.. Source Code.. Submitting Patches.. News.. Tweet.. Dart brings structure to web app engineering with a new language, libraries, and tools.. Read about our new M1 release!.. Download now.. Circle +Dart.. Subscribe.. Follow @dart_lang.. Familiar.. Dart is a.. class-based, object-oriented language.. with lexical scoping, closures, and optional static typing.. Dart helps you build structured modern web apps and is.. easy to learn.. for a wide range of developers.. Learn more.. import.. dart:html.. ;.. main.. ().. {.. var.. msg.. =.. query.. (.. #msg.. );.. btn.. new.. ButtonElement.. ();.. text.. Click me!.. on.. click.. add.. ((.. e.. ).. =.. Dart!.. document.. body.. nodes.. }.. });.. Productive.. Dart Editor and the SDK provide an.. integrated development and debugging.. experience.. The editor supports refactoring, breakpoints, code completion, code navigation, and more.. The SDK contains the stand-alone virtual machine, a package manager, and Chromium with an embedded Dart VM.. Ubiquitous.. Dart can be.. compiled to JavaScript.. , so you can use it for web apps in all modern desktop and mobile browsers.. Our JavaScript compiler generates minimal code thanks to tree-shaking.. Dart apps can also.. run on the server.. , in a stand-alone Dart VM.. Start.. Get the editor and SDK.. Read the technical overview.. Tour the samples.. Watch an intro video.. Learn.. Follow the language tour.. Follow the library tour.. See synonyms to JavaScript.. Read a free eBook.. Practice a codelab.. Participate.. Send feedback to the mailing list.. Follow on G+.. and.. Twitter.. Get answers at Stack Overflow.. File feature requests and bugs.. Submit a patch.. Overview.. A structured language.. that's flexible and familiar.. Dart addresses issues with traditional web development languages while remaining easy to learn.. Thanks to optional static types, Dart scales from simple scripts to large apps.. Learn more with the.. language tour.. , or read the.. language spec.. Classes.. Lexical closures.. Optional static types.. Named parameters.. Isolates.. More.. dart:math.. class.. Point.. final.. num.. x.. ,.. y.. this.. zero.. :.. 0.. // Named constructor.. // with an initializer list.. distanceTo.. other.. dx.. -.. dy.. return.. sqrt.. *.. +.. Dart supports classes as a fundamental structural building block for libraries and  ...   to express with a single type annotation.. Type annotations don't affect the runtime semantics.. optional types in Dart.. flipFlags.. ({.. bool.. up.. hidden.. false.. }).. on:.. true.. up:.. hidden:.. // Named params are also optional params.. // up == null, hidden == false.. The meaning of.. or.. is hard to decipher without context.. Using named parameters, you can write code that is easier to understand.. As a bonus, named parameters are also optional parameters.. dart:isolate.. echo.. port.. receive.. SendPort.. replyTo.. send.. Echo:.. $.. echoService.. spawnFunction.. call.. Hello!.. then.. answer.. print.. ));.. Create isolates for concurrent programming and to run third-party code more securely.. Communicate between isolates by passing messages that are copied before received to ensure no state is ever shared.. Dart uses isolates instead of shared-state threads for safer parallel programming.. echo().. function is run in an isolate, which is created with.. A message is sent by.. and an answer is printed.. The Dart language contains many more useful and productive features.. Check out a sample:.. better asynchronous programming with.. Futures.. more explicit collections with.. generics.. better.. for loops.. error handling with.. exceptions.. Learn more about the Dart language by taking a.. , or reading the.. Dart Language Spec.. Productive and integrated tools.. for faster development.. Gone are the days of building web apps with plain text editors.. Dart Editor.. , its static analysis engine, and direct integration with Chromium+DartVM helps you develop, debug, and maintain your apps.. Dart also ships a stand-alone.. Dart SDK.. that contains the.. dart2js compiler.. , the.. for running command-line apps, and the.. pub.. package manager.. Code completion.. Explore the methods and fields available to the object you're working on.. Refactoring.. Change your code structure without changing the behavior.. Outline view.. List the classes, methods, and functions in a simple tree display.. Debugger.. Set breakpoints, inspect variables, and step over, into, and out of code.. Static analysis.. See warnings when inconsistencies and potential problems are detected.. Find callers.. Quickly find all callers for a method, and easily jump to those locations.. Get Started Now.. Download Dart Editor.. Read the Technical Overview.. Join the Mailing List.. Dart Docs.. Articles and Tutorials.. Dart Tools.. Dart Resources.. Dart Development.. Except as otherwise.. noted.. , the content of this page is licensed under the.. Creative Commons Attribution 3.. 0 License.. , and code samples are licensed under the.. BSD License.. Terms of Service.. Privacy Policy..

    Original link path: /
    Open archive

  • Title: Chapter 2. A Tour of the Dart Language | Dart: Structured web apps
    Descriptive info: An excerpt from.. Dart: Up and Running.. Chapter 2.. A Tour of the Dart Language.. This chapter shows you how to use each major Dart feature, from variables and operators to classes and libraries, with the assumption that you already know how to program in another language.. Tip:.. To play with each feature, create a server application project in Dart Editor, as described in.. Up and running.. Consult the.. Dart Language Specification.. whenever you want more details about a language feature.. Contents.. A basic Dart program.. Important concepts.. Variables.. Built-in types.. Functions.. Operators.. Control flow statements.. Exceptions.. Generics.. Libraries and visibility.. Typedefs.. Comments.. Summary.. The following code uses many of Dart’s most basic features.. // Define a function.. printNumber(num aNumber) { print('The number is $aNumber.. '); // Print to the console.. } // This is where the app starts executing.. main() { var number = 42; // Declare and initialize a variable.. printNumber(number); // Call a function.. Here’s what this program uses that applies to all (or almost all) Dart apps:.. This is a comment.. Use // to indicate that the rest of the line is a comment.. Alternatively, use /*.. */.. For details, see.. A type.. Some of the other built-in types are String, int, and bool.. 100.. A number.. literal.. Literals are a kind of compile-time constant.. print().. A handy way to display output.. '.. '.. (or.. ".. ".. A string literal.. variableName.. ${.. expression.. String interpolation: including a variable or expression’s string equivalent inside of a string literal.. For more information, see.. Strings.. main().. The special,.. required.. , top-level function where app execution starts.. A way to declare a variable without specifying its type.. Note:.. Our code follows the conventions in the.. Dart Style Guide.. For example, we use two-space indentation.. As you learn about the Dart language, keep these facts and concepts in mind:.. Everything you can place in a variable is an.. object.. , and every object is an instance of a.. Even numbers and functions are objects.. All objects inherit from the.. Object.. Specifying static types (such as.. in the preceding example) clarifies your intent and enables static checking by tools, but it’s optional.. (You might notice when you’re debugging your code that objects with no specified type get a special type:.. dynamic.. ).. Dart parses all your code before running it.. You can provide tips to Dart—for example, by using types or compile-time constants—to catch errors or help your code run faster.. Dart supports top-level functions (such as main()), as well as functions tied to a class or object (.. static.. instance methods.. , respectively).. Similarly, Dart supports top-level.. variables.. , as well as variables tied to a class or object (static and instance variables).. Instance variables are sometimes known as.. fields.. properties.. Unlike Java, Dart doesn’t have the keywords.. public.. ,.. protected.. , and.. private.. If an identifier starts with an underscore (_), it’s private to its library.. Identifiers.. can start with a letter or _, followed by any combination of those characters plus digits.. Sometimes it matters whether something is an.. or a.. statement.. , so we’ll be precise about those two words.. Dart tools can report two kinds of errors: warnings and errors.. Warnings are just hints that your code might not work, but they don’t prevent your program from executing.. Errors can be either compile-time or run-time.. A compile-time error prevents the code from executing at all; a run-time error results in an exception.. being raised while the code executes.. Dart has two.. runtime modes.. : production and checked.. Production is faster, but checked is helpful at development.. Runtime modes.. We recommend that you develop and debug in checked mode, and deploy to production mode.. Production mode.. is the default runtime mode of a Dart program, optimized for speed.. Production mode ignores assert statements.. Assert.. and static types.. Checked mode.. is a developer-friendly mode that helps you catch some type errors during runtime.. For example, if you assign a non-number to a variable declared as a.. , then checked mode throws an exception.. Here’s an example of creating a variable and assigning a value to it:.. var name = 'Bob';.. Variables are references.. The variable called.. name.. contains a reference to a String object with a value of.. “.. Bob.. ”.. Default value.. Uninitialized variables have an initial value of.. null.. Even variables with numeric types are initially null, because numbers are objects.. int lineCount; assert(lineCount == null); // Variables (even if they will be numbers) are initially null.. The assert() call is ignored in production mode.. In checked mode,.. assert(.. condition.. throws an exception unless.. is true.. Optional types.. You have the option of adding static types to your variable declarations:.. String name = 'Bob';.. Adding types is a way to clearly express your intent.. Tools such as compilers and editors can use these types to help you, by providing early warnings for bugs and code completion.. This chapter follows the.. style guide recommendation.. of using.. , rather than type annotations, for local variables.. Final and const.. If you never intend to change a variable, use.. const.. , either instead of.. or in addition to a type.. A final variable can be set only once; a const variable is a compile-time constant.. A local, top-level, or class variable that’s declared as.. is initialized the first time it’s used.. final name = 'Bob'; // Or: final String name = 'Bob'; // name = 'Alice'; // Uncommenting this results in an error.. Lazy initialization of final variables helps apps start up faster.. Use.. for variables that you want to be compile-time constants.. Where you declare the variable, set the value to a compile-time constant such as a literal, a const variable, or the result of an arithmetic operation on constant numbers.. const bar = 1000000; // Unit of pressure (in dynes/cm2) const atm = 1.. 01325 * bar; // Standard atmosphere.. The Dart language has special support for the following types:.. numbers.. strings.. booleans.. lists (also known as.. arrays.. maps.. You can initialize an object of any of these special types using a literal.. For example,.. 'this is a string'.. is a string literal, and.. is a boolean literal.. Because every variable in Dart refers to an object—an instance of a.. —you can usually use.. constructors.. to initialize variables.. Some of the built-in types have their own constructors.. For example, you can use the Map() constructor to create a map, using code such as.. new Map().. Numbers.. Dart numbers come in two flavors:.. int.. Integers of arbitrary size.. double.. 64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard.. Both.. are subtypes of.. The num type includes basic operators such as +, -, /, and *, as well as bitwise operators such as.. The num type is also where you’ll find abs(), ceil(), and floor(), among other methods.. If num and its subtypes don’t have what you’re looking for, the.. Math.. class might.. Integers are numbers without a decimal point.. Here are some examples of defining integer literals:.. var x = 1; var hex = 0xDEADBEEF; var bigInt = 346534658346524376592384765923749587398457294759347029438709349347;.. In JavaScript produced from Dart code, big integers currently behave differently than they do when the same Dart code runs in the Dart VM.. http://dartbug.. com/1533.. If a number includes a decimal, it is a double.. Here are some examples of defining double literals:.. var y = 1.. 1; var exponents = 1.. 42e5;.. Here’s how you turn a string into a number, or vice versa:.. // String - int var one = int.. parse('1'); assert(one == 1); // String - double var onePointOne = double.. parse('1.. 1'); assert(onePointOne == 1.. 1); // int - String String oneAsString = 1.. toString(); assert(oneAsString == '1'); // double - String String piAsString = 3.. 14159.. toStringAsFixed(2); assert(piAsString == '3.. 14');.. The num type specifies the traditional bitwise shift ( , ), AND ( ), and OR (|) operators.. For example:.. assert((3 1) == 6); // 0011 1 == 0110 assert((3 1) == 1); // 0011 1 == 0001 assert((3 | 4) == 7); // 0011 | 0100 == 0111.. A Dart string is a sequence of UTF-16 code units.. You can use either single or double quotes to create a string:.. var s1 = 'Single quotes work well for string literals.. '; var s2 = "Double quotes work just as well.. "; var s3 = 'It\'s easy to escape the string delimiter.. '; var s4 = "It's even easier to just use the other string delimiter.. ";.. You can put the value of an expression inside a string by using ${.. If the expression is an identifier, you can skip the {}.. To get the string corresponding to an object, Dart calls the object’s toString() method.. var s = 'string interpolation'; assert('Dart has $s, which is very handy.. ' == 'Dart has string interpolation, which is very handy.. '); assert('That deserves all caps.. ${s.. toUpperCase()} is very handy!' == 'That deserves all caps.. STRING INTERPOLATION is very handy!');.. operator tests whether two objects are equivalent.. Two strings are equivalent if they have the same characters.. You can concatenate strings using adjacent string literals:.. var s = 'String ''concatenation' " works even over line breaks.. "; assert(s == 'String concatenation works even over line breaks.. ');.. Another way to create a multi-line string: use a triple quote with either single or double quotation marks.. var s1 = ''' You can create multi-line strings like this one.. '''; var s2 = """This is also a multi-line string.. """;.. You can create a.. raw.. string by prefixing it with.. r.. var s = r"In a raw string, even \n isn't special.. For more information on using strings, see.. Strings and regular expressions.. Booleans.. To represent boolean values, Dart has a type named.. Only two objects have type bool: the boolean literals,.. When Dart expects a boolean value, only the value.. is treated as true.. All other values are treated as false.. Unlike in JavaScript, values such as.. 1.. "aString".. someObject.. are all treated as false.. For example, consider the following code, which is valid both as JavaScript and as Dart code:.. var name = 'Bob'; if (name) { print('You have a name!'); // Prints in JavaScript, not in Dart.. If you run this code as JavaScript, without compiling to Dart, it prints.. You have a name!.. because.. is a non-null object.. However, in Dart running in.. production mode.. , the above doesn’t print at all because.. is converted to.. (because.. name != true.. In Dart running in.. checked mode.. , the above code throws an exception because the.. variable is not a bool.. Here’s another example of code that behaves differently in JavaScript and Dart:.. if (1) { print('JavaScript prints this line because it thinks 1 is true.. '); } else { print('Dart in production mode prints this line.. '); // However, in checked mode, if (1) throws an exception // because 1 is not boolean.. The previous two samples work only in production mode, not checked mode.. In checked mode, an exception is thrown if a non-boolean is used when a boolean value is expected.. Dart’s treatment of booleans is designed to avoid the strange behaviors that can arise when many values can be treated as true.. What this means for you is that, instead of using code like.. if (.. nonbooleanValue.. , you should instead explicitly check for values.. // Check for an empty string.. var fullName = ''; assert(fullName.. isEmpty()); // Check for zero.. var hitPoints = 0; assert(hitPoints = 0); // Check for null.. var unicorn; assert(unicorn == null); // Check for NaN.. var iMeantToDoThis = 0/0; assert(iMeantToDoThis.. isNaN());.. Lists.. Perhaps the most common collection in nearly every programming language is the.. array.. , or ordered group of objects.. In Dart, arrays are.. List.. objects, so we usually just call them.. lists.. Dart list literals look like JavaScript array literals.. Here’s a simple Dart list:.. var list = [1,2,3];.. Lists use zero-based indexing, where 0 is the index of the first element and.. list.. length - 1.. is the index of the last element.. You can get a list’s length and refer to list elements just as you would in JavaScript:.. var list = [1,2,3]; assert(list.. length == 3); assert(list[1] == 2);.. The List type and its supertype,.. Collection.. , have many handy methods for manipulating lists.. For more information about lists, see.. Collections.. Maps.. In general, a map is an object that associates keys and values.. Dart support for maps is provided by map literals and the.. Map.. type.. Here’s a simple Dart map:.. var gifts = { // A map literal // Keys Values 'first' : 'partridge', 'second' : 'turtledoves', 'fifth' : 'golden rings' };.. In map literals, each.. key.. must be a string.. If you use a Map constructor, any object can be a key.. var map = new Map(); // use a map constructor.. map[1] = 'partridge'; // key is 1; value is 'partridge'.. map[2] = 'turtledoves'; // key is 2; value is 'turtledoves'.. map[5] = 'golden rings'; // key is 5; value is 'golden rings'.. A map.. value.. can be any object, including null.. You add a new key-value pair to an existing map just as you would in JavaScript:.. var gifts = { 'first': 'partridge' }; gifts['fourth'] = 'calling birds'; // Add a key-value pair.. You retrieve a value from a map the same way you would in JavaScript:.. var gifts = { 'first': 'partridge' }; assert(gifts['first'] == 'partridge');.. If you look for a key that isn’t in a map, you get a null in return.. var gifts = { 'first': 'partridge' }; assert(gifts['fifth'] == null);.. length.. to get the number of key-value pairs in the map:.. var gifts = { 'first': 'partridge' }; gifts['fourth'] = 'calling birds'; assert(gifts.. length == 2);.. For more information about maps, see.. Here’s an example of implementing a function:.. void printNumber(num number) { print('The number is $number.. '); }.. Although the style guide recommends specifying the parameter and return types, you don’t have to:.. printNumber(number) { // Omitting types is OK.. print('The number is $number.. For functions that contain just one expression, you can use a shorthand syntax:.. printNumber(number) = print('The number is $number.. expr.. syntax is a shorthand for.. { return.. ;}.. In the printNumber() function above, the expression is the call to the top-level print() function.. Only an.. —not a.. —can appear between the arrow (= ) and the semicolon (;).. For example, you can’t put an if statement.. If and else.. there, but you can use a conditional (?:) expression.. Other operators.. You can use types with = , although the convention is not to do so.. printNumber(num number) = print('The number is $number.. '); // Including types is OK.. Here’s an example of calling a function:.. printNumber(123);.. A function can have two types of parameters: required and optional.. The required parameters are listed first, followed by any optional parameters.. Optional parameters.. Optional parameters can be either positional or named, but not both.. Both kinds of optional parameter can have default values.. The default values must be compile-time constants such as literals.. If no default value is provided, the value is.. If you need to know whether the caller passed in a value for an optional parameter, use the syntax.. ?.. param.. if (?device) { // Returns true if the caller specified the parameter.. //.. The user set the value.. Do something with it.. Optional named parameters.. When calling a function, you can specify named parameters using.. paramName.. :.. enableFlags(bold: true, hidden: false);.. When defining a function, use.. param1.. param2.. , …}.. to specify named parameters.. /// Sets the [bold] and [hidden] flags to the values you specify.. enableFlags({bool bold, bool hidden}) { //.. Use a colon (.. ) to specify default values.. /** * Sets the [bold] and [hidden] flags to the values you specify, * defaulting to false.. */ enableFlags({bool bold: false, bool hidden: false}) { //.. } enableFlags(bold: true); // bold will be true; hidden will be false.. The preceding two examples use documentation comments.. Documentation comments.. Optional positional parameters.. Wrapping a set of function parameters in.. [].. marks them as optional positional parameters.. String say(String from, String msg, [String device]) { var result = '$from says $msg'; if (device != null) { result = '$result with a $device'; } return result; }.. Here’s an example of calling this function without the optional parameter:.. assert(say('Bob', 'Howdy') == 'Bob says Howdy');.. And here’s an example of calling this function with the third parameter:.. assert(say('Bob', 'Howdy', 'smoke signal') == 'Bob says Howdy with a smoke signal');.. to specify default values.. String say(String from, String msg, [String device='carrier pigeon', String mood]) { var result = '$from says $msg'; if (device != null) { result = '$result with a $device'; } if (mood != null) { result = '$result (in a $mood mood)'; } return result; } assert(say('Bob', 'Howdy') == 'Bob says Howdy with a carrier pigeon');.. Functions as first-class objects.. You can pass a function as a parameter to another function.. printElement(element) { print(element); } var list = [1,2,3]; list.. forEach(printElement); // Pass printElement as a parameter.. You can also assign a function to a variable, such as:.. var loudify = (msg) = '!!! ${msg.. toUpperCase()} !!!'; assert(loudify('hello') == '!!! HELLO !!!');.. Functions can close over variables defined in surrounding scopes.. In the following example, makeAdder() captures the variable.. n.. and makes it available to the function that makeAdder() returns.. Wherever the returned function goes, it remembers.. /// Returns a function that adds [n] to the function's argument.. Function makeAdder(num n) { return (num i) = n + i; } main() { var add2 = makeAdder(2); // Create a function that adds 2.. var add4 = makeAdder(4); // Create a function that adds 4.. assert(add2(3) == 5); assert(add4(3) == 7); }.. Return values.. All functions return a value.. If no return value is specified, the statement.. return null;.. is implicitly appended to the function body.. Dart defines the operators shown in.. Table 2-1.. You can override many of these operators, as described in.. Operators and their precedence.. Description.. Operator.. unary postfix and argument definition test.. ++.. -- () [].. identifier.. unary prefix.. !.. ~.. ++.. --.. multiplicative.. * / % ~/.. additive.. + -.. shift.. relational and type test.. = = as is is!.. equality.. == !=.. bitwise AND.. bitwise XOR.. ^.. bitwise OR.. |.. logical AND.. logical OR.. ||.. conditional.. expr1.. ?.. expr2.. expr3.. cascade.. assignment.. = *= /= ~/= %= += -= = = = ^= |=.. When you use operators, you create.. expressions.. Here are some examples of operator expressions:.. a++ a + b a = b a == b a? b: c a is T.. In.. , each operator has higher precedence than the operators in the rows below it.. For example, the multiplicative operator.. %.. has higher precedence than (and thus executes before) the equality operator.. , which has higher precedence than the logical AND operator.. That precedence means that the following two lines of code execute the same way:.. if ((n % i == 0) (d % i == 0)) // Parens improve readability.. if (n % i == 0 d % i == 0) // Harder to read, but equivalent.. Warning:.. For operators that work on two operands, the leftmost operand determines which version of the operator is used.. For example, if you have a Vector  ...   ($x, $y)'); } }.. The right-hand side of an initializer does not have access to.. Redirecting constructors.. Sometimes a constructor’s only purpose is to redirect to another constructor in the same class.. A redirecting constructor’s body is empty, with the constructor call appearing after a colon (:).. y); // The main constructor for this class.. alongXAxis(num x) : this(x, 0); // Delegates to the main constructor.. Constant constructors.. If your class produces objects that never change, you can make these objects compile-time constants.. To do this, define a.. constructor and make sure that all instance variables are.. class ImmutablePoint { final num x; final num y; const ImmutablePoint(this.. y); static final ImmutablePoint origin = const ImmutablePoint(0, 0); }.. Factory constructors.. factory.. keyword when implementing a constructor that doesn’t always create a new instance of its class.. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype.. The following example demonstrates a factory constructor returning objects from a cache.. class Logger { final String name; bool mute = false; // _cache is library-private, thanks to the _ in front of its name.. static final Map String, Logger _cache = String, Logger {}; factory Logger(String name) { if (_cache.. containsKey(name)) { return _cache[name]; } else { final logger = new Logger.. _internal(name); _cache[name] = logger; return logger; } } Logger.. _internal(this.. name); void log(String msg) { if (!mute) { print(msg); } } }.. Factory constructors have no access to.. To invoke a factory constructor, you use the.. keyword:.. var logger = new Logger('UI'); logger.. log('Button clicked');.. Methods.. Methods are functions that provide behavior for an object.. Instance methods.. Instance methods on objects can access instance variables and.. The distanceTo() method in the following sample is an example of an instance method.. y); num distanceTo(Point other) { var dx = x - other.. x; var dy = y - other.. y; return sqrt(dx * dx + dy * dy); } }.. Getters and setters are special methods that provide read and write access to an object’s properties.. Recall that each instance variable has an implicit getter, plus a setter if appropriate.. You can create additional properties by implementing getters and setters, using the.. get.. set.. keywords.. class Rectangle { num left; num top; num width; num height; Rectangle(this.. left, this.. top, this.. width, this.. height); // Define two calculated properties: right and bottom.. num get right = left + width; set right(num value) = left = value - width; num get bottom = top + height; set bottom(num value) = top = value - height; } main() { var rect = new Rectangle(3, 4, 20, 15); assert(rect.. left == 3); rect.. right = 12; assert(rect.. left == -8); }.. With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code.. Operators such as increment (++) work in the expected way, whether or not a getter is explicitly defined.. To avoid any unexpected side effects, the operator calls the getter exactly once, saving its value in a temporary variable.. Abstract methods.. Instance, getter, and setter methods can be abstract, defining an interface but leaving its implementation up to other classes.. To make a method abstract, use a semicolon (;) instead of a method body.. abstract class Doer { //.. Define instance variables and methods.. void doSomething(); // Define an abstract method.. } class EffectiveDoer extends Doer { void doSomething() { //.. Provide an implementation, so the method is not abstract in this class.. } }.. Calling an abstract method results in a run-time error.. Also see.. Abstract classes.. You can override the operators shown in.. Table 2-10.. For example, if you define a Vector class, you might define a + method to add two vectors.. Operators that can be overridden.. []=.. Here’s an example of a class that overrides the.. operators.. class Vector { final int x; final int y; const Vector(this.. y); Vector operator +(Vector v) { // Overrides + (a + b).. return new Vector(x + v.. x, y + v.. y); } Vector operator -(Vector v) { // Overrides - (a - b).. return new Vector(x - v.. x, y - v.. y); } } main() { final v = new Vector(2,3); final w = new Vector(2,2); assert(v.. x == 2 v.. y == 3); // v == (2,3) assert((v+w).. x == 4 (v+w).. y == 5); // v+w == (4,5) assert((v-w).. x == 0 (v-w).. y == 1); // v-w == (0,1) }.. For an example of overriding.. , see.. Implementing map keys.. abstract.. modifier to define an.. abstract class.. —a class that can’t be instantiated.. Abstract classes are useful for defining interfaces, often with some implementation.. If you want your abstract class to appear to be instantiable, define a factory constructor.. Abstract classes often have abstract methods.. Here’s an example of declaring an abstract class that has an abstract method.. // This class is declared abstract and thus can't be instantiated.. abstract class AbstractContainer { //.. Define constructors, fields, methods.. void updateChildren(); // Abstract method.. The following class isn’t abstract, and thus can be instantiated even though it defines an abstract method.. class SpecializedContainer extends AbstractContainer { //.. Define more constructors, fields, methods.. void updateChildren() { //.. Implement updateChildren().. } void doSomething(); // Abstract method causes a warning but doesn't prevent instantiatation.. Implicit interfaces.. Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements.. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.. A class implements one or more interfaces by declaring them in an.. implements.. clause and then providing the APIs required by the interfaces.. // A person.. The implicit interface contains greet().. class Person { final _name; // In the interface, but visible only in this library, thanks to _.. Person(this.. _name); // Not in the interface, since this is a constructor.. String greet(who) = 'Hello, $who.. I am $_name.. '; // In the interface.. } // An implementation of the Person interface.. class Imposter implements Person { final _name = ""; // We have to define this, but we don't use it.. String greet(who) = 'Hi $who.. Do you know who I am?'; } greetBob(Person person) = person.. greet('bob'); main() { print(greetBob(new Person('kathy'))); print(greetBob(new Imposter())); }.. Here’s an example of specifying that a class implements multiple interfaces:.. class Point.. implements Comparable, Location.. { //.. Extending a class.. to create a subclass, and.. super.. to refer to the superclass.. class Television { void turnOn() { _illuminateDisplay(); _activateIrSensor(); } } class SmartTelevision extends Television { void turnOn() { super.. turnOn(); _bootNetworkInterface(); _initializeMemory(); _upgradeApps(); } }.. Subclasses can override instance methods, getters, and setters.. Class variables and methods.. keyword to implement class-wide variables and methods.. Static variables.. Static variables (class variables) are useful for class-wide state and constants.. class Color { static const RED = const Color('red'); // A constant static variable.. final String name; // An instance variable.. const Color(this.. name); // A constant constructor.. } main() { assert(Color.. RED.. name == 'red'); }.. Static variables aren’t initialized until they’re used.. Static methods.. Static methods (class methods) do not operate on an instance, and thus do not have access to.. y); static num distanceBetween(Point a, Point b) { var dx = a.. x - b.. x; var dy = a.. y - b.. y; return sqrt(dx * dx + dy * dy); } } main() { var a = new Point(2, 2); var b = new Point(4, 4); var distance = Point.. distanceBetween(a,b); assert(distance 2.. 9 distance 2.. 8); }.. Consider using top-level functions, instead of static methods, for common or widely used utilities and functionality.. You can use static methods as compile-time constants.. For example, you can pass a static method as a parameter to a constant constructor.. If you look at the API documentation for the basic array type,.. List,.. you’ll see that the type is actually.. List E.. notation marks List as a.. generic.. parameterized.. ) type—a type that has formal type parameters.. By convention, type variables have single-letter names, such as E, T, S, K, and V.. Why use generics?.. Because types are optional in Dart, you never.. have.. to use generics.. You might.. want.. to, though, for the same reason you might want to use other types in your code: types (generic or not) let you document and annotate your code, making your intent clearer.. For example, if you intend for a list to contain only strings, you can declare it as.. List String.. (read that as.. list of string.. That way you, your fellow programmers, and your tools (such as Dart Editor and the Dart VM in checked mode) can detect that assigning a non-string to the list is probably a mistake.. var names = new List String (); names.. addAll(['Seth', 'Kathy', 'Lars']); //.. names.. add(42); // Fails in checked mode (succeeds in production mode).. Another reason for using generics is to reduce code duplication.. Generics let you share a single interface and implementation between many types, while still taking advantage of checked mode and static analysis early warnings.. For example, say you create an interface for caching an object:.. abstract class ObjectCache { Object getByKey(String key); setByKey(String key, Object value); }.. You discover that you want a string-specific version of this interface, so you create another interface:.. abstract class StringCache { String getByKey(String key); setByKey(String key, String value); }.. Later, you decide you want a number-specific version of this interface.. You get the idea.. Generic types can save you the trouble of creating all these interfaces.. Instead, you can create a single interface that takes a type parameter:.. abstract class Cache T { T getByKey(String key); setByKey(String key, T value); }.. In this code, T is the stand-in type.. It’s a placeholder that you can think of as a type that a developer will define later.. Using collection literals.. List and map literals can be parameterized.. Parameterized literals are just like the literals you’ve already seen, except that you add.. (for lists) or.. keyType.. valueType.. (for maps) before the opening bracket.. You might use parameterized literals when you want type warnings in checked mode.. Here is example of using typed literals:.. var names = String ['Seth', 'Kathy', 'Lars']; var pages = String, String { 'index.. html':'Homepage', 'robots.. txt':'Hints for web robots', 'humans.. txt':'We are people, not machines' };.. Map literals always have string.. keys.. , so their type is always.. String,.. SomeType.. Using constructors.. To specify one or more types when using a constructor, put the types in angle brackets (.. ) just after the class name.. addAll(['Seth', 'Kathy', 'Lars']); var nameSet = new Set String.. from(names);.. The following code creates a map that has integer keys and values of type View:.. var views = new Map int, View ();.. Generic collections and the types they contain.. Dart generic types are.. reified.. , which means that they carry their type information around at runtime.. For example, you can test the type of a collection, even in production mode:.. addAll(['Seth', 'Kathy', 'Lars']); print(names is List String ); // true.. However, the.. expression checks the type of the.. collection.. only—not of the objects inside it.. In production mode, a List String might have some non-string items in it.. The solution is to either check each item’s type or wrap item-manipulation code in an exception handler (see.. In contrast, generics in Java use.. erasure.. , which means that generic type parameters are removed at runtime.. In Java, you can test whether an object is a List, but you can’t test whether it’s a List String.. For more information about generics, see.. Optional Types in Dart.. part.. directives can help you create a modular and shareable code base.. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore (_) are visible only inside the library.. Every Dart app is a library.. , even if it doesn’t use a library directive.. Libraries can be distributed using packages.. pub: The Dart package manager.. for information about pub, a package manager included in the SDK.. Using libraries.. to specify how a namespace from one library is used in the scope of another library.. For example, Dart web apps generally use the.. dart:html.. library, which they can import like this:.. import 'dart:html';.. The only required argument to.. is a URI.. [.. ].. specifying the library.. For built-in libraries, the URI has the special.. dart:.. scheme.. For other libraries, you can use a file system path or the.. package:.. scheme specifies libraries provided by a package manager such as the pub tool.. import 'dart:io'; import 'package:mylib/mylib.. dart'; import 'package:utils/utils.. dart';.. Specifying a library prefix.. If you import two libraries that have conflicting identifiers, then you can specify a prefix for one or both libraries.. For example, if library1 and library2 both have an Element class, then you might have code like this:.. import 'package:lib1/lib1.. dart'; import 'package:lib2/lib2.. dart' as lib2; //.. var element1 = new Element(); // Uses Element from lib1.. var element2 = new lib2.. Element(); // Uses Element from lib2.. Importing only part of a library.. If you want to use only part of a library, you can selectively import the library.. dart' show foo, bar; // Import only foo and bar from lib1.. import 'package:lib2/lib2.. dart' hide foo; // Import all names EXCEPT foo from lib2.. Implementing libraries.. directive to specify the files that are part of a library, and.. to specify that a file declares a library.. Using multiple files.. Whether or not you specify a.. directive, you can use.. to specify the files that implement the current library.. // No library directive; this file defines an anonymous library.. part 'ball.. dart'; // Part of this library's implementation is in ball.. part 'util.. dart'; // Another part is in util.. import 'dart:html'; // This app uses the HTML library.. main() { // Having a main() method makes this an app (and thus a library).. Declaring a library.. To explicitly declare a library, use a.. library ballgame; // Declare that this is a library.. main() { // We could move this code to another file in this library.. Associating a file with a library.. You can use.. followed by.. of.. part of.. ) in implementation files to specify that the file is associated with a library.. Using.. is optional, but it helps tools such as Dart Editor.. Here’s an example of using.. // In ballgame.. dart: library ballgame; import 'dart:utf'; //.. Other imports go here.. dart'; part 'util.. dart'; //.. // In ball.. dart: part of ballgame; //.. code goes here.. // In util.. Re-exporting libraries.. You can combine or repackage libraries by re-exporting part or all of them.. For example, you might have a huge library that you implement as a set of smaller libraries.. Or you might create a library that provides a subset of methods from another library.. // In french.. dart:.. library french; hello() = print('Bonjour!'); goodbye() = print('Au Revoir!');.. // In togo.. library togo; import 'french.. dart'; export 'french.. dart' show hello;.. // In another.. dart file:.. import 'togo.. dart'; void main() { hello(); //print bonjour goodbye(); //FAIL }.. Modern web browsers, even on mobile platforms, run on multi-core CPUs.. To take advantage of all those cores, developers traditionally use shared-memory threads running concurrently.. However, shared-state concurrency is error prone and can lead to complicated code.. Instead of threads, all Dart code runs inside of.. isolates.. Each isolate has its own memory heap, ensuring that no isolate’s state is accessible from any other isolate.. Learn more about isolates in.. dart:isolate - Concurrency with isolates.. In Dart, functions are objects, just like strings and numbers are objects.. typedef.. function-type alias.. , gives a function type a name that you can use when declaring fields and return types.. A typedef retains type information when a function type is assigned to a variable.. Consider the following code, which does not use a typedef.. class SortedCollection { Function compare; SortedCollection(int f(Object a, Object b)) { compare = f; } } int sort(Object a, Object b) =.. ; // Initial, broken implementation.. main() { SortedCollection collection = new SortedCollection(sort); // All we know is that compare is a function, but what type of function? assert(collection.. compare is Function); }.. Type information is lost when assigning.. f.. to.. compare.. The type of.. is.. (Object, Object).. →.. (where.. means returns), yet the type of.. is Function.. If we change the code to use explicit names and retain type information, both developers and tools can use that information.. typedef int Compare(Object a, Object b);.. class SortedCollection { Compare compare; SortedCollection(this.. compare); } int sort(Object a, Object b) =.. main() { SortedCollection collection = new SortedCollection(sort); assert(collection.. compare is Function); assert(collection.. compare is Compare); }.. Currently, typedefs are restricted to function types.. We expect this to change.. Because typedefs are simply aliases, they offer a way to check the type of any function.. typedef int Compare(int a, int b); int sort(int a, int b) = a - b; main() { assert(sort is Compare); // True! }.. Dart supports single-line comments, multi-line comments, and documentation comments.. Single-line comments.. A single-line comment begins with.. Everything between.. and the end of line is ignored by the Dart compiler.. main() { // TODO: refactor into an AbstractLlamaGreetingFactory? print('Welcome to my Llama farm!'); }.. Multi-line comments.. A multi-line comment begins with.. /*.. and ends with.. is ignored by the Dart compiler (unless the comment is a documentation comment; see the next section).. Multi-line comments can nest.. main() { /* * This is a lot of work.. Consider raising chickens.. Llama larry = new Llama(); larry.. feed(); larry.. exercise(); larry.. clean(); */ }.. Documentation comments are multi-line or single-line comments that begin with.. /**.. ///.. on consecutive lines has the same effect as a multi-line doc comment.. Inside a documentation comment, the Dart compiler ignores all text unless it is enclosed in brackets.. Using brackets, you can refer to classes, methods, fields, top-level variables, functions, and parameters.. The names in brackets are resolved in the lexical scope of the documented program element.. Here is an example of documentation comments with references to other classes and arguments:.. /** * The llama (Lama glama) is a domesticated South American * camelid, widely used as a meat and pack animal by Andean * cultures since pre-Hispanic times.. */ class Llama { String name; /** * Feeds your llama [Food].. * * The typical llama eats one bale of hay per week.. */ void feed(Food food) { //.. } /// Exercises your llama with an [activity] for /// [timeLimit] minutes.. void exercise(Activity activity, int timeLimit) { //.. In the generated documentation,.. [Food].. becomes a link to the API docs for the Food class.. To parse Dart code and generate HTML documentation, you can use Dart Editor, which in turn uses the SDK’s dartdoc package.. For an example of generated documentation, see the.. Dart API documentation.. This chapter summarized the commonly used features in the Dart language.. For more information about the language, see the.. articles.. such as.. Idiomatic Dart.. ].. URI stands for.. uniform resource identifier.. URLs (.. uniform resource locators.. ) are a common kind of URI.. The content of this page is licensed under the.. Creative Commons Attribution-Noncommercial-No Derivative Works 3.. 0 United States License..

    Original link path: /docs/dart-up-and-running/ch02.html
    Open archive

  • Title: Language Specification | Dart: Structured web apps
    Descriptive info: Language Specification.. You can read.. The Dart Programming Language Specification.. in PDF and HTML formats:.. PDF.. HTML.. (from Google Docs).. The current version (0.. 12, M1) was released October 15, 2012.. See the specification's change log (section 1.. 2) for a list of differences between versions..

    Original link path: /docs/spec/
    Open archive

  • Title: Chapter 3. A Tour of the Dart Libraries | Dart: Structured web apps
    Descriptive info: Chapter 3.. A Tour of the Dart Libraries.. This chapter shows you how to use the major features in Dart’s libraries.. It’s just an overview, and by no means comprehensive.. Whenever you need more details about a class, consult the.. Dart API reference.. Expect major changes to the Dart libraries before Dart’s first production release.. dart:core - Numbers, collections, strings, and more.. Sets.. Common collection methods.. Dates and times.. Utility classes.. Asynchronous programming.. dart:math - Math and random.. dart:html - Browser-based apps.. Manipulating the DOM.. Using HTTP resources with HttpRequest.. Sending and receiving real-time data with WebSockets.. Isolate concepts.. Using isolates.. Spawning isolates.. Sending messages.. Sending any type of object.. Receiving messages.. Receiving replies.. Keeping the root isolate alive.. dart:io - I/O for command-line apps.. Files and directories.. HTTP clients and servers.. dart:json - Encoding and decoding objects.. dart:uri - Manipulating URIs.. dart:utf - Strings and Unicode.. dart:crypto - Hash codes and more.. The Dart core library provides a small but critical set of built-in functionality.. This library is automatically imported into every Dart program.. The dart:core library defines the num, int, and double classes, which have some basic utilities for working with numbers.. You can convert a string into an integer or double with the parse() methods of int and double, respectively.. assert(int.. parse('42') == 42); assert(double.. parse('0.. 50') == 0.. 5);.. Use the toString() method (defined by.. ) to convert an int or double to a string.. To specify the number of digits to the right of the decimal, use toStringAsFixed() (defined by num).. To specify the number of significant digits in the string, use toStringAsPrecision() (also in num).. // Convert an int to a string.. assert(42.. toString() == '42'); // Convert a double to a string.. assert(123.. 456.. toString() == '123.. 456'); // Specify the number of digits after the decimal.. toStringAsFixed(2) == '123.. 46'); // Specify the number of significant figures.. toStringAsPrecision(2) == '1.. 2e+2'); assert(double.. 2e+2') == 120.. 0);.. For more information, see the API documentation for.. int,.. double,.. A string in Dart is an immutable sequence of UTF-16 code units.. The language tour has more information about strings.. You can use regular expressions (RegExp objects) to search within strings and to replace parts of strings.. The String class defines such methods as split(), contains(), startsWith(), endsWith(), and more.. Searching inside a string.. You can find particular locations within a string, as well as check whether a string begins with or ends with a particular pattern.. // Check whether a string contains another string.. assert('Never odd or even'.. contains('odd')); // Does a string start with another string? assert('Never odd or even'.. startsWith('Never')); // Does a string end with another string? assert('Never odd or even'.. endsWith('even')); // Find the location of a string inside a string.. indexOf('odd') == 6);.. Extracting data from a string.. You can get the individual characters or character codes from a string as Strings or ints, respectively.. You can also extract a substring or split a string into a list of substrings.. // Grab a substring.. substring(6, 9) == 'odd'); // Split a string using a string pattern.. var parts = 'structured web apps'.. split(' '); assert(parts.. length == 3); assert(parts[0] == 'structured'); // Get the character (as a string) by index.. assert('Never odd or even'[0] == 'N'); // Use splitChars() to get a list of all characters (as Strings); // good for iterating.. for (var char in 'hello'.. splitChars()) { print(char); } // Get the char code at an index.. charCodeAt(0) == 78); // Get all the char codes as a list of integers.. var charCodes = 'Never odd or even'.. charCodes(); assert(charCodes.. length == 17); assert(charCodes[0] == 78);.. Converting to uppercase or lowercase.. You can easily convert strings to their uppercase and lowercase variants.. // Convert to uppercase.. assert('structured web apps'.. toUpperCase() == 'STRUCTURED WEB APPS'); // Convert to lowercase.. assert('STRUCTURED WEB APPS'.. toLowerCase() == 'structured web apps');.. Trimming and empty strings.. Remove all leading and trailing white space with trim().. To check whether a string is empty (length is zero), use isEmpty().. // Trim a string.. assert(' hello '.. trim() == 'hello'); // Check whether a string is empty.. assert(''.. isEmpty()); // Strings with only white space are not empty.. assert(!' '.. isEmpty());.. Replacing part of a string.. Strings are immutable objects, which means you can create them but you can’t change them.. If you look closely at the.. String API docs.. , you’ll notice that none of the methods actually changes the state of a String.. For example, the method replaceAll() returns a new String without changing the original String.. var greetingTemplate = 'Hello, NAME!'; var greeting = greetingTemplate.. replaceAll(new RegExp('NAME'), 'Bob'); assert(greeting != greetingTemplate); // greetingTemplate didn't change.. Building a string.. To programmatically generate a string, you can use StringBuffer.. A StringBuffer doesn’t generate a new String object until toString() is called.. var sb = new StringBuffer(); sb.. add('Use a StringBuffer '); sb.. addAll(['for ', 'efficient ', 'string ', 'creation ']); sb.. add('if you are ').. add('building lots of strings.. '); var fullString = sb.. toString(); assert(fullString == 'Use a StringBuffer for efficient string creation ' 'if you are building lots of strings.. '); sb.. clear(); // All gone! assert(sb.. toString() == '');.. Regular expressions.. The RegExp class provides the same capabilities as JavaScript regular expressions.. Use regular expressions for efficient searching and pattern matching of strings.. // A regular expression for one or more digits var numbers = const RegExp(r'\d+'); var allCharacters = 'llamas live fifteen to twenty years'; var someDigits = 'llamas live 15 to 20 years'; // Contains() can use a regular expression.. assert(!allCharacters.. contains(numbers)); assert(someDigits.. contains(numbers)); // Replace every match with another string.. var exedOut = someDigits.. replaceAll(numbers, 'XX'); assert(exedOut == 'llamas live XX to XX years');.. You can work directly with the RegExp class, too.. The Match class provides access to a regular expression match.. var numbers = const RegExp(r'\d+'); var someDigits = 'llamas live 15 to 20 years'; // Check whether the reg exp has a match in a string.. assert(numbers.. hasMatch(someDigits)); // Loop through all matches.. for (var match in numbers.. allMatches(someDigits)) { print(match.. group(0)); // 15, then 20 }.. More information.. Refer to the.. for a full list of methods.. Also see the API docs for.. StringBuffer,.. Pattern,.. RegExp,.. Match.. Dart ships with a core collections API, which includes classes for lists, sets, and maps.. As the language tour shows.. , you can use literals to create and initialize lists.. Alternatively, use one of the List constructors.. The List class also defines several methods for adding items to and removing items from lists.. // Use a List constructor.. var vegetables = new List(); // Or simply use a list literal.. var fruits = ['apples', 'oranges']; // Add to a list.. fruits.. add('kiwis'); // Add multiple items to a list.. addAll(['grapes', 'bananas']); // Get the list length.. assert(fruits.. length == 5); // Remove a single item.. var appleIndex = fruits.. indexOf('apples'); fruits.. removeAt(appleIndex); assert(fruits.. length == 4); // Remove all elements from a list.. clear(); assert(fruits.. length == 0);.. Use indexOf() to find the index of an object in a list.. var fruits = ['apples', 'oranges']; // Access a list item by index.. assert(fruits[0] == 'apples'); // Find an item in a list.. indexOf('apples') == 0);.. Sort a list using the sort() method.. You must provide a sorting function that compares two objects.. This sorting function must return 0 for.. smaller.. , 0 for the.. same.. , and 0 for.. bigger.. The following example uses compareTo(), which is defined by.. Comparable.. and implemented by String.. var fruits = ['bananas', 'apples', 'oranges']; // Sort a list.. sort((a, b) = a.. compareTo(b)); assert(fruits[0] == 'apples');.. Lists are parameterized types, so you can specify the type that a list should contain.. // This list should contain only strings.. var fruits = new List String (); fruits.. add('apples'); var fruit = fruits[0]; assert(fruit is String); // Generates static analysis warning, num is not a string.. add(5); // BAD: Throws exception in checked mode.. List API docs.. A set in Dart is an unordered collection of unique items.. Because a set is unordered, you can’t get a set’s items by index (position).. var ingredients = new Set(); ingredients.. addAll(['gold', 'titanium', 'xenon']); assert(ingredients.. length == 3); // Adding a duplicate item has no effect.. ingredients.. add('gold'); assert(ingredients.. length == 3); // Remove an item from a set.. remove('gold'); assert(ingredients.. Use contains() and containsAll() to check whether one or more objects are in a set.. addAll(['gold', 'titanium', 'xenon']); // Check whether an item is in the set.. assert(ingredients.. contains('titanium')); // Check whether all the items are in the set.. containsAll(['titanium', 'xenon']));.. An intersection is a set whose items are in two other sets.. A subset has all of its items included in another, potentially larger, collection.. addAll(['gold', 'titanium', 'xenon']); // Create the intersection of two sets.. var nobleGases = new Set.. from(['xenon', 'argon']); var intersection = ingredients.. intersection(nobleGases); assert(intersection.. length == 1); assert(intersection.. contains('xenon')); // Check whether this set is a subset of another collection.. // That is, does another collection contains all the items of this set? var allElements = ['hydrogen', 'helium', 'lithium', 'beryllium', 'gold', 'titanium', 'xenon' /* all the rest */]; assert(ingredients.. isSubsetOf(allElements));.. Set API docs.. Both List and Set extend the Collection class.. As such, they share common functionality found in all collections.. The following examples work with any object that implements Collection.. Use isEmpty() to check whether a collection has no items.. var teas = ['green', 'black', 'chamomile', 'earl grey']; assert(!teas.. To apply a function to each item in a collection, you can use forEach().. Or use map() if you want a new collection that contains the results.. var teas = ['green', 'black', 'chamomile', 'earl grey']; teas.. forEach((tea) = print('I drink $tea')); var loudTeas = teas.. map((tea) = tea.. toUpperCase()); assert(loudTeas.. some((tea) = tea == 'GREEN'));.. Use some() and every() to check whether some or all items in a collection match a condition.. var teas = ['green', 'black', 'chamomile', 'earl grey']; // Chamomile is not caffeinated.. isDecaffeinated(String teaName) = teaName == 'chamomile'; // Use filter() to create a new collection with only the items // that return true from the provided function.. var decaffeinatedTeas = teas.. filter((tea) = isDecaffeinated(tea)); // or teas.. filter(isDecaffeinated) // Use some() to check whether at least one item in the collection // satisfies a condition.. assert(teas.. some(isDecaffeinated)); // Use every() to check whether all the items in a collection // satisfy a condition.. assert(!teas.. every(isDecaffeinated));.. Collection API docs.. A map, commonly known as a.. dictionary.. hash.. , is an unordered collection of key-value pairs.. Maps associate a key to some value for easy retrieval.. Unlike in JavaScript, Dart objects are not maps.. The Map class does not itself extend Collection.. You can, however, get a collection of a map’s keys or its values.. You can declare a map using a terse literal syntax, or you can use a traditional constructor.. // Map literals use strings as keys.. var hawaiianBeaches = { 'oahu' : ['waikiki', 'kailua', 'waimanalo'], 'big island' : ['wailea bay', 'pololu beach'], 'kauai' : ['hanalei', 'poipu'] }; // Maps can be built from a constructor.. var searchTerms = new Map(); // Maps are parameterized types; you can specify what types // the key and value should be.. var nobleGases = new Map int, String ();.. You add, get, and set map items using the bracket syntax.. Use remove() to remove a key and its value from a map.. var nobleGases = new Map int, String (); // Maps from constructors can use any object as a key.. // Integers and strings are common key types.. nobleGases[54] = 'xenon'; // Retrieve a value with a key.. assert(nobleGases[54] == 'xenon'); // Check whether a map contains a key.. assert(nobleGases.. containsKey(54)); // Remove a key and its value.. nobleGases.. remove(54); assert(!nobleGases.. containsKey(54));.. You can retrieve all the values or all the keys from a map.. var hawaiianBeaches = { 'oahu' : ['waikiki', 'kailua', 'waimanalo'], 'big island' : ['wailea bay', 'pololu beach'], 'kauai' : ['hanalei', 'poipu'] }; // Get all the keys as an unordered collection (a list).. var keys = hawaiianBeaches.. getKeys(); assert(keys.. length == 3); assert(new Set.. from(keys).. contains('oahu')); // Get all the values as an unordered collection (a list of lists).. var values = hawaiianBeaches.. getValues(); assert(values.. length == 3); assert(values.. some((v) = v.. indexOf('waikiki') != -1));.. You can also iterate through the key-value pairs.. // NOTE: Do not depend on iteration order.. hawaiianBeaches.. forEach((k,v) { print('I want to visit $k and swim at $v'); // I want to visit oahu and swim at [waikiki, kailua, waimanalo], etc.. To check whether a map contains a key, use containsKey().. Because map values can be null, you cannot rely on simply getting the value for the key and checking for null to determine the existence of a key.. var hawaiianBeaches = { 'oahu' : ['waikiki', 'kailua', 'waimanalo'], 'big island' : ['wailea bay', 'pololu beach'], 'kauai' : ['hanalei', 'poipu'] }; assert(hawaiianBeaches.. containsKey('oahu')); assert(!hawaiianBeaches.. containsKey('florida'));.. Use the putIfAbsent() method when you want to assign a value to a key if and only if the key does not already exist in a map.. You must provide a function that returns the value.. var teamAssignments = {}; teamAssignments.. putIfAbsent('Catcher', () = pickToughestKid()); assert(teamAssignments['Catcher'] != null);.. Map API docs.. A Date object is a point in time.. The time zone is either UTC or the local time zone.. You can create Date objects using several constructors.. // Get the current date and time.. var now = new Date.. now(); // Create a new Date with the local time zone.. var y2k = new Date(2000, 1, 1, 0, 0, 0, 0); // You can also use named parameters.. y2k = new Date(2000, month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0); // Specify all the parts of a date as a UTC time.. y2k = new Date(2000, 1, 1, 0, 0, 0, 0, isUtc: true); // Specify a UTC date and time in milliseconds since the Unix epoch.. y2k = new Date.. fromMillisecondsSinceEpoch(946684800000, isUtc: true); // Parse an ISO 8601 date.. fromString('2000-01-01T00:00:00Z');.. millisecondsSinceEpoch.. property of a date returns the number of milliseconds since the epoch.. var y2k = new Date.. fromString('2000-01-01T00:00:00Z'); assert(y2k.. millisecondsSinceEpoch == 946684800000);.. Use the Duration class to calculate the difference between two dates and to shift a date’s time forward or backwards.. fromString('2000-01-01T00:00:00Z'); // Add one year.. var y2001 = y2k.. add(const Duration(days: 366)); assert(y2001.. year == 2001); // Subtract 30 days.. var december2000 = y2001.. subtract(const Duration(days: 30)); assert(december2000.. year == 2000); assert(december2000.. month == 12); // Calculate the difference between two dates.. // Returns a Duration object.. var duration = y2001.. difference(y2k); assert(duration.. inDays == 366); // y2k was a leap year.. Refer to the API docs for.. Date.. Duration.. The core library contains various utility classes, useful for sorting, mapping values, and iterating.. Comparing objects.. Implement the.. interface to indicate that an object can be compared to another object, usually for sorting.. The compareTo() method returns 0 for.. class Line implements Comparable { final length; const Line(this.. length); int compareTo(Line other) = length - other.. length; } main() { var short = const Line(1); var long = const Line(100); assert(short.. compareTo(long) 0); }.. Each object in Dart automatically provides an integer hash code, and thus can be used as a key in a map.. However, you can override the hashCode() method to generate a custom hash code.. If you do, be sure to override the.. operator, as well.. Objects that are equal (via.. ) must have identical hash codes.. A hash code doesn’t have to be unique, but it should be well distributed.. class Person { String firstName, lastName; Person(this.. firstName, this.. lastName); // Override hashCode using strategy from Effective Java, Chapter 11.. int hashCode() { int result = 17; result = 37 * result + firstName.. hashCode(); result = 37 * result + lastName.. hashCode(); return result; } // Always implement operator== if you override hashCode.. bool operator==(other) { if (identical(other, this)) return true; return (other.. firstName == firstName other.. lastName == lastName); } } main() { var p1 = new Person('bob', 'smith'); var p2 = new Person('bob', 'smith'); assert(p1.. hashCode() == p2.. hashCode()); }.. Iterable.. Iterator.. classes support for-in loops.. Implement Iterable to signal that an object can provide an Iterator, and thus be used by for-in loops.. Implement Iterator to define the actual iteration ability.. class Process { // Represents a process.. } class ProcessIterator implements Iterator Process { Process next() { // Return the next process if possible; but if not: throw new NoMoreElementsException(); } bool hasNext() { // True if calling next() would return a process return false; } } // A mythical class that lets you iterate through all processes.. class Processes implements Iterable Process { Iterator Process iterator() { return new ProcessIterator(); } } main() { // Objects that implement Iterable can be used with for-in.. for (var process in new Processes()) { // Do something with the process.. Asynchronous programming often uses callback functions, but Dart provides an alternative:.. Future.. objects.. A Future is like a promise for a result to be provided sometime in the future.. You have the option of using a.. Completer.. to produce a Future and, later, to supply a value to the Future.. Future bool longExpensiveSearch() { var completer = new Completer(); // Perform exhaustive search.. // Sometime later, // found it!! completer.. complete(true); return completer.. future; } main() { var result = longExpensiveSearch(); // Returns immediately.. // result.. then() returns immediately.. result.. then((success) { // The following code executes when the operation is complete.. print('The item was found: $success'); }); }.. Chaining multiple asynchronous methods.. The Future class specifies a chain() method, which is a useful way to specify that multiple asynchronous methods run in a certain order.. Future result = costlyQuery(); result.. handleException((exception) = print('DOH!')); result.. chain((value) = expensiveWork()).. chain((value) = lengthyComputation()).. then((value) = print('done!'));.. In the above example, the methods run in the following order:.. costlyQuery().. expensiveWork().. lengthyComputation().. Waiting for multiple futures.. Sometimes your algorithm needs to initiate many asynchronous methods and wait for each one to complete before continuing.. class to manage multiple Futures and wait for them  ...   can manipulate the same object instance.. Because state is managed by individual isolates, no locks or mutexes are needed, greatly simplifying concurrent programming.. To use isolates, you should understand the following concepts:.. No two isolates ever share the same thread at the same time.. Within an isolate, callbacks execute one at a time, making the code more predictable.. All values in memory, including globals, are available only to their isolate.. No isolate can see or manipulate values owned by another isolate.. The only way isolates can communicate with each other is by passing messages.. Isolates send messages using SendPorts, and receive them using ReceivePorts.. The content of a message can be any of the following:.. A primitive value (null, num, bool, double, String).. An instance of SendPort.. A list or map whose elements are any of the above, including other lists and maps.. In special circumstances.. , an object of any type.. Each isolate has a ReceivePort, which is available as the.. variable.. Because all Dart code runs inside an isolate, even main() has access to a port object.. When a web application is compiled to JavaScript, its isolates can be implemented as Web workers.. When running in Dartium, isolates run in the VM.. In the standalone VM, the main() function runs in the first isolate (also known as the.. root isolate.. When the root isolate terminates, it terminates the whole VM, regardless of whether other isolates are still running.. To use an isolate, you import the.. dart:isolate.. library, spawn a new isolate, and then send and receive messages.. Any top-level function or static method.. is a valid entry point for an isolate.. The entry point should not expect arguments and should return void.. It is illegal to use a function closure as an entry point to an isolate.. Pass the entry point to spawnFunction().. import 'dart:isolate'; runInIsolate() { print('hello from an isolate!'); } main() { spawnFunction(runInIsolate); // Note: incomplete.. // Use a ReceivePort (details below) to keep the root isolate alive // long enough for runInIsolate() to perform its work.. We plan to support spawning an isolate from code at a URI.. Send a message to an isolate via a SendPort.. The spawnFunction() method returns a handle to the newly created isolate’s SendPort.. To simply send a message, use send().. import 'dart:isolate'; echo() { // Receive messages here.. (See the next section.. ) } main() { var sendPort = spawnFunction(echo); sendPort.. send('Hello from main'); // Note: incomplete.. // Use a ReceivePort (details below) to keep the root isolate alive // long enough for echo() to perform its work.. In special circumstances (such as when using spawnFunction() inside the Dart VM), it is possible to send any type of object to an isolate.. The object message is copied when sent.. Use a ReceivePort to receive messages sent to an isolate.. Obtain a handle to the default ReceivePort from the top-level.. You can also create new instances of ReceivePort, if you want to route messages to different ports and callbacks.. Handle an incoming message with a callback function passed to the receive() method.. import 'dart:isolate'; echo() { port.. receive((msg, reply) { print('I received: $msg'); }); } main() { var sendPort = spawnFunction(echo); sendPort.. Use the call() method on SendPort as a simple way to send a message and receive a reply.. The call() method returns a Future for the reply.. receive((msg, reply) { reply.. send('I received: $msg'); }); } main() { var sendPort = spawnFunction(echo); sendPort.. call('Hello from main').. then((reply) { print(reply); // I received: Hello from main }); }.. Under the covers, the call() method creates and manages a SendPort and a ReceivePort, which are necessary for a call-and-response message exchange.. In the VM, an isolate continues to run as long as it has an open ReceivePort inside the isolate.. If the main() function only starts other isolates, doing no work itself, you must keep the root isolate alive to keep the program alive.. To keep a root isolate alive, open a ReceivePort in the root isolate.. When all the child isolates have finished their work, you can send a message to the root isolate to close its ReceivePort, thus stopping the program.. You can coordinate isolates with message passing, sending a message to inform the root isolate when a child isolate finishes.. Here is an example:.. import 'dart:isolate'; childIsolate() { port.. receive((msg, replyTo) { print('doing some work'); if (replyTo != null) replyTo.. send('shutdown'); }); } main() { var sender = spawnFunction(childIsolate); var receiver = new ReceivePort(); receiver.. receive((msg, _) { if (msg == 'shutdown') { print('shutting down'); receiver.. close(); } }); sender.. send('do work please', receiver.. toSendPort()); }.. In the above example, the child isolate runs to completion because the root isolate keeps a ReceivePort open.. The root isolate creates a ReceivePort to wait for a shutdown message.. The term shutdown is arbitrary; the ReceivePort simply needs to wait for some signal.. Once the root isolate receives a shutdown message, it closes the ReceivePort.. With the ReceivePort closed and nothing else to do, the root isolate terminates, causing the app to exit.. See the API docs for the.. dart:isolate library,.. as well as for.. ReceivePort.. dart:io library.. provides APIs to deal with files, directories, processes, sockets, and HTTP connections.. Only command-line apps can use dart:io—not web apps.. In general, the dart:io library implements and promotes an asynchronous API.. Synchronous methods can easily block the event loop, making it difficult to scale server applications.. Therefore, most operations return results via callbacks or Future objects, a pattern common with modern server platforms such as Node.. js.. The few synchronous methods in the dart:io library are clearly marked with a Sync suffix on the method name.. We don’t cover them here.. Only command-line apps can import and use.. dart:io.. The I/O library enables command-line apps to read and write files and browse directories.. You have two choices for reading the contents of a file: all at once, or streaming.. Reading a file all at once requires enough memory to store all the contents of the file.. If the file is very large or you want to process it while reading it, you should use an InputStream, as described in.. Streaming file contents.. Reading a file as text.. When reading a text file, you can read the entire file contents with readAsText().. When the individual lines are important, you can use readAsLines().. In both cases, a Future object is returned that provides the contents of the file as one or more strings.. import 'dart:io'; main() { var config = new File('config.. txt'); // Put the whole file in a single string.. config.. readAsText(Encoding.. UTF_8).. then((String contents) { print('The entire file is ${contents.. length} characters long'); }); // Put each line of the file into its own string.. readAsLines(Encoding.. then((List String lines) { print('The entire file is ${lines.. length} lines long'); }); }.. Reading a file as binary.. The following code reads an entire file as bytes into a list of ints.. The call to readAsBytes() returns a Future, which provides the result when it’s available.. txt'); config.. readAsBytes().. then((List int contents) { print('The entire file is ${contents.. length} bytes long'); }); }.. Handling errors.. Errors are thrown as exceptions if you do not register an explicit handler.. If you want to capture an error, you can register a.. handleException.. handler with the Future object.. txt'); Future readFile = config.. readAsText(); readFile.. handleException((e) { print(e); //.. Other error handling goes here.. return true; // We've handled the exception; no need to propagate it.. }); readFile.. then((text) = print(text)); }.. Use an InputStream to read a file, a little at a time.. onData.. callback runs when data is ready to be read.. When the InputStream is finished reading the file, the.. onClosed.. callback executes.. txt'); var inputStream = config.. openInputStream(); inputStream.. onError = (e) = print(e); inputStream.. onClosed = () = print('file is now closed'); inputStream.. onData = () { List int bytes = inputStream.. read(); print('Read ${bytes.. length} bytes from stream'); }; }.. To decode an input stream from bytes into characters, wrap the InputStream with a.. StringInputStream.. You can read the strings either as data becomes available or a line at a time.. Writing file contents.. Use an OutputStream to write data to a file.. Open a file for writing with openOutputStream() and declare a mode.. FileMode.. WRITE.. to completely overwrite existing data in the file, and.. APPEND.. to add to the end.. import 'dart:io'; main() { var logFile = new File('log.. txt'); var out = logFile.. openOutputStream(FileMode.. WRITE); out.. writeString('FILE ACCESSED ${new Date.. now()}'); out.. close(); }.. To write binary data, use.. write(List int buffer).. Listing files in a directory.. Finding all files and subdirectories for a directory is an asynchronous operation.. The list() method returns a DirectoryLister, on which you can register callback handlers to be notified when a file is encountered (using.. onFile.. ) or when a directory is encountered (using.. onDir.. import 'dart:io'; main() { var dir = new Directory('/tmp'); DirectoryLister lister = dir.. list(recursive:true); // Returns immediately.. lister.. onError = (e) = print(e); lister.. onFile = (String name) = print('Found file $name'); lister.. onDir = (String name) = print('Found dir $name'); }.. Other common functionality.. The File and Directory classes contain other functionality, including but not limited to:.. Creating a file or directory: create() in File and Directory.. Deleting a file or directory: delete() in File and Directory.. Getting the length of a file: length() in File.. Getting random access to a file: open() in File.. File,.. Directory,.. DirectoryLister.. InputStream.. OutputStream.. Besides the APIs discussed in this section, the dart:io library also provides APIs for.. processes.. sockets.. web sockets.. For more examples of using dart:io, see.. The dart:io library provides classes that command-line apps can use for accessing HTTP resources, as well as running HTTP servers.. HTTP server.. HttpServer.. class provides the low-level functionality for building web servers.. You can match request handlers, set headers, stream data, and more.. Because Dart is single threaded and has an event loop, the API design of HttpServer favors callbacks for handling events.. The following sample web server can return only simple text information.. This server listens on port 8888 and address 127.. 1 (localhost), responding to requests for the path.. /languages/dart.. All other requests are handled by the default request handler, which returns a response code of 404 (not found).. import 'dart:io'; main() { dartHandler(HttpRequest request, HttpResponse response) { print('New request'); response.. outputStream.. writeString('Dart is optionally typed'); response.. close(); }; var httpServer = new HttpServer(); httpServer.. addRequestHandler( (req) = req.. path == '/languages/dart', dartHandler); httpServer.. listen('127.. 1', 8888); }.. You can see a more comprehensive HTTP server in.. The server’s code.. HTTP client.. HttpClient.. class helps you connect to HTTP resources from your Dart command-line or server-side application.. You can set headers, use HTTP methods, and read and write data.. The HttpClient class does not work in browser-based apps.. When programming in the browser, use the HttpRequest class.. The HttpClient API, like the HttpServer API, is callback oriented.. The general flow of events is as follows:.. Create a new HttpClient.. Get the URL.. Register the onResponse() callback on the HttpClientConnection.. Register the onData() callback on the input stream.. Register the onClosed() callback on the HttpClientConnection.. Read data when available.. Shut down the HttpClient when you no longer want to create connections using it.. import 'dart:io'; import 'dart:uri'; main() { var httpClient = new HttpClient(); var conn = httpClient.. getUrl(new Uri('http://127.. 1:8888/languages/dart')); conn.. onResponse = (HttpClientResponse resp) { var input = resp.. inputStream; input.. onData = () { var data = input.. read(); var text = new String.. fromCharCodes(data); print(text); }; input.. onClosed = () = httpClient.. shutdown(); }; }.. JSON.. is a simple text format for representing structured objects and collections.. JSON library.. decodes JSON-formatted strings into Dart objects, and encodes objects into JSON-formatted strings.. The Dart JSON library works in both web apps and command-line apps.. To use the JSON library, import.. dart:json.. Decoding JSON.. Decode a JSON-encoded string into a Dart object with JSON.. parse().. import 'dart:json'; main() { // NOTE: Be sure to use double quotes ("), not single quotes ('), // inside the JSON string.. This string is JSON, not Dart.. var jsonString = ''' [ {"score": 40}, {"score": 80} ] '''; var scores = JSON.. parse(jsonString); assert(scores is List); var firstScore = scores[0]; assert(firstScore is Map); assert(firstScore['score'] == 40); }.. Encoding JSON.. Encode a supported Dart object into a JSON-formatted string with JSON.. stringify().. Only objects of type int, double, String, bool, null, List, or Map can be encoded into JSON.. List and Map objects are encoded recursively.. If any object that isn’t an int, double, String, bool, null, List, or Map is passed to stringify(), the object’s toJson() method is called.. If toJson() returns an encodable value, that value is encoded in the object’s place.. import 'dart:json'; main() { var scores = [ {'score': 40}, {'score': 80}, {'score': 100, 'overtime': true, 'special_guest': null} ]; var jsonText = JSON.. stringify(scores); assert(jsonText == '[{"score":40},{"score":80},' '{"score":100,"overtime":true,' '"special_guest":null}]'); }.. URI library.. provides functions to encode and decode strings for use in URIs (which you might know as.. URLs.. These functions handle characters that are special for URIs, such as.. Another part of the URI library is the Uri class, which parses and exposes the components of a URI—domain, port, scheme, and so on.. The URI library works in both web apps and command-line apps.. To use it, import.. dart:uri.. Encoding and decoding fully qualified URIs.. To encode and decode characters.. except.. those with special meaning in a URI (such as.. #.. ), use the top-level encodeUri() and decodeUri() functions.. These functions are good for encoding or decoding a fully qualified URI, leaving intact special URI characters.. import 'dart:uri'; main() { var uri = 'http://example.. org/api?foo=some message'; var encoded = encodeUri(uri); assert(encoded == 'http://example.. org/api?foo=some%20message'); var decoded = decodeUri(encoded); assert(uri == decoded); }.. Notice how only the space between.. some.. was encoded.. Encoding and decoding URI components.. To encode and decode all of a string’s characters that have special meaning in a URI, including (but not limited to).. , use the top-level encodeUriComponent() and decodeUriComponent() functions.. org/api?foo=some message'; var encoded = encodeUriComponent(uri); assert(encoded == 'http%3A%2F%2Fexample.. org%2Fapi%3Ffoo%3Dsome%20message'); var decoded = decodeUriComponent(encoded); assert(uri == decoded); }.. Notice how every special character is encoded.. is encoded to.. %2F.. Parsing URIs.. You can parse a URI into its parts with the Uri() constructor.. import 'dart:uri'; main() { var uri = new Uri('http://example.. org:8080/foo/bar#frag'); assert(uri.. scheme == 'http'); assert(uri.. domain == 'example.. org'); assert(uri.. path == '/foo/bar'); assert(uri.. fragment == 'frag'); assert(uri.. origin == 'http://example.. org:8080'); }.. See the.. Uri API docs.. for more URI components that you can get.. Building URIs.. You can build up a URI from individual parts using the Uri.. fromComponents() constructor.. import 'dart:uri'; main() { var uri = new Uri.. fromComponents(scheme: 'http', domain: 'example.. org', path: '/foo/bar', fragment: 'frag'); assert(uri.. toString() == 'http://example.. org/foo/bar#frag'); }.. The UTF library helps bridge the gap between strings and UTF-8/UTF-16/UTF-32 encodings.. The UTF library works in both web apps and command-line apps.. To use the UTF library, import.. dart:utf.. Decoding UTF-8 characters.. Use decodeUtf8() to decode UTF8-encoded bytes to a Dart string.. import 'dart:utf'; main() { var string = decodeUtf8([0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9, 0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4, 0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1]); print(string); // 'Îñţérñåţîöñåļîžåţîờñ' }.. Encoding strings to UTF-8 bytes.. Use encodeUtf8() to encode a Dart string as a list of UTF8-encoded bytes.. import 'dart:utf'; main() { List int expected = [0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9, 0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4, 0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1]; List int encoded = encodeUtf8('Îñţérñåţîöñåļîžåţîờñ'); assert(() { if (encoded.. length != expected.. length) return false; for (int i = 0; i encoded.. length; i++) { if (encoded[i] != expected[i]) return false; } return true; }); }.. Other functionality.. The UTF library can decode and encode UTF-16 and UTF-32 bytes.. For details, see the.. API docs for the UTF library.. Dart crypto library.. contains functions useful for cryptographic applications, such as creating cryptographic hashes and generating hash-based message authentication codes.. The crypto library works in both web apps and command-line apps.. To use the crypto library, import.. dart:crypto.. Generating cryptographic hashes.. With the crypto library, you can use.. SHA256,.. SHA1,.. MD5.. objects to generate hashes (also known as.. digests.. message digests.. We recommend using SHA256, but we have included SHA1 and MD5 for compatibility with older systems.. All these types inherit from.. Hash,.. which defines the Dart interface for.. cryptographic hash functions.. import 'dart:crypto'; main() { var sha256 = new SHA256(); var digest = sha256.. update('message'.. charCodes()).. digest(); var hexString = CryptoUtils.. bytesToHex(digest); assert(hexString == 'ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d'); }.. If the message content changes, the digest value also changes (with a very high probability).. Generating message authentication codes.. Use a hash-based message authentication code (.. HMAC.. ) to combine a cryptographic hash function with a secret key.. import 'dart:crypto'; main() { var hmac = new HMAC(new SHA256(), 'secretkey'.. charCodes()); var hmacDigest = hmac.. digest(); var hmacHex = CryptoUtils.. bytesToHex(hmacDigest); assert(hmacHex == '5c3e2f56de9411068f675ef32ffa12735210b9cbfee2ba521367a3955334a343'); }.. If either the message contents or key changes, the digest value also changes (with a very high probability).. Generating Base64 strings.. You can represent binary data as a character string by using the.. Base64.. encoding scheme.. Use the CryptoUtils.. bytesToBase64() utility method to convert a list of bytes into a Base64-encoded string.. import 'dart:crypto'; import 'dart:io'; main() { var file = new File('icon.. ico'); var bytes = file.. readAsBytesSync(); var base64 = CryptoUtils.. bytesToBase64(bytes); assert(base64 == 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38G' 'IAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='); }.. This chapter introduced you to the most commonly used functionality in Dart’s built-in libraries.. You can use the pub tool, discussed in the next chapter, to install additional Dart libraries.. The dart2js compiler and the Dart VM do not yet support static methods as isolate entry points.. com/3011.. Support for sending an arbitrary object to an isolate is not yet available when compiling to JavaScript..

    Original link path: /docs/dart-up-and-running/ch03.html
    Open archive

  • Title: Articles | Dart: Structured web apps
    Descriptive info: Articles.. Read these articles for insight into Dart programming topics.. Everyday Dart.. Bob Nystrom, October 2011 (updated October 2012).. How we format, structure, and organize our code.. Get a sense of how to write Dart code like a native.. Benchmarking the Dart VM.. John McCutchan, October 2012.. Learn how to benchmark your Dart application.. A Game of Darts Tutorials.. Mary Campione, Ongoing.. Beginner's guide to web programming using Dart.. Language Details.. Emulating Functions in Dart.. Gilad Bracha, January 2012 (updated November 2012).. Learn how you'll be able to create classes that can substitute for functions.. Milestone 1 Language Changes.. Bob Nystrom, July 2012 (updated September 2012).. A brief introduction to some language changes made for the M1 target.. Dart Puzzlers.. Josh Bloch, February 2012.. See what happens when the author of Java Puzzlers translates each puzzler to Dart.. Gilad Bracha, October 2011.. Learn what Dart's dynamic type system does and doesn't do, and get tips for using types.. Libraries and APIs.. Dart Web Components.. Siggi Cherem, October 2012.. Use Dart  ...   classes using the Dart unit test library.. Unit Tests with Dart.. Graham Wheeler, June 2012.. Write both synchronous and asynchronous tests using the Dart unit test library.. Native Extensions for the Standalone Dart VM.. William Hesse, May 2012.. Use shared libraries written in C or C++ from your Dart command-line apps.. An Introduction to the dart:io Library.. Mads Ager, March 2012.. Learn how your server-side Dart code can use the dart:io library to perform asynchronous I/O using files, sockets, HTTP connections, and more.. Improving the DOM.. Bob Nystrom, October 2011.. See what our new API for working with the DOM looks like in Dart.. Embedding Dart in HTML.. Sigmund Cherem and Vijay Menon, October 2011.. Find out how you'll be able to embed Dart directly on HTML pages.. Design Decisions.. Why Dart Types are Optional and Unsound.. Eli Brandt, December 2011.. Understand why Dart's type system works the way it does.. Why Not a Bytecode VM?.. Florian Loitsch and Bob Nystrom, November 2011.. Understand one of Dart's key architectural decisions..

    Original link path: /articles/
    Open archive

  • Title: A Game of Darts—Tutorials | Dart: Structured web apps
    Descriptive info: Contents.. A Game of Darts: Home.. 1: Get Started.. 2: Connect Dart HTML.. 3: Add an Element to the DOM.. What's the point?.. This blue box shows page highlights.. Learn Dart here: No web experience required.. Dart is an open-source platform for building structured HTML5 web apps.. Welcome to your guide to building great web apps using Dart.. Under construction.. This is a draft.. Your kindly worded.. comments and suggestions.. are appreciated.. Thank you for your patience.. A Game of Darts.. is a collection of tutorials,.. targets.. , that teaches you how to build web programs using the Dart language, tools, and APIs.. You can either follow the targets in order, building your knowledge of Dart and web programming from the ground up, or customize your learning experience by choosing just the targets you need.. You  ...   will learn about it here, starting with the basic concepts in Target 2.. Target 1: Get Started.. Download the Dart software bundle, discover which tools and libraries come with the Dart software, and use Dart Editor to run two apps.. Target 2: Connect Dart HTML.. Use Dart Editor to create a stripped-down Dart program that simply puts text on a browser page.. Though simple, this tiny program shows you how to host a Dart program on a web page and one way to manipulate the DOM.. You will also begin learning about the Dart language, Dart Editor, HTML, and CSS.. Target 3: Add an Element to the DOM.. The small app in this target responds to a user-generated event by adding an Element to the DOM.. more targets coming.. Version: 6 Nov 2012.. Send feedback.. Get Started..

    Original link path: /docs/tutorials/
    Open archive

  • Title: FAQ | Dart: Structured web apps
    Descriptive info: Frequently Asked Questions (FAQ).. Collected by Eli Brandt.. Version 0.. 02, February 2012.. This FAQ answers many of the questions we've been asked about Dart.. However, because we released Dart as an early technology preview rather than keeping it under wraps until version 1.. 0, some important open questions remain.. We hope to address them with upcoming work and experimentation, inside and outside of Google.. Strategy.. Why Dart?.. Is the language really what needs to be fixed in web development?.. Is Dart going to divert community effort from JavaScript-based web development?.. Is Google planning to put Dart under the control of a standards body?.. Until that point, how will you be taking input on changes to Dart?.. Why didn't Google make Dart an open standard right from the start?.. What's the future for GWT?.. Why didn't Google build a bytecode VM targetable by multiple languages including Dart?.. Isn't Dart a lot like JavaScript?.. Isn't Dart a lot like Java?.. How does Dart compare with using the Closure compiler on JavaScript?.. How does Dart compare with CoffeeScript?.. How does Dart relate to Go?.. Why isn't Dart more like Haskell / Smalltalk / Python / Scala / other language?.. Why isn't Dart syntax more exciting?.. Is it really a dynamic language if it doesn't have eval() or adding fields to a value at run time?.. Can Dart add reflection?.. Can Dart add tuples, pattern matching, non-nullable types, interface duck typing, partial evaluation, optional semicolons,.. ?.. Types.. Does Dart have type inference?.. Why are type annotations optional?.. Why is the type system designed to be unsound?.. But don't you need sound typing information to get high performance?.. Why do type annotations have no effect on the runtime behavior?.. Why are generics covariant?.. Usage and tools.. Should I write my web app in Dart?.. How does Dart code interoperate with JavaScript libraries?.. I have a large JavaScript codebase.. How would I migrate it to Dart?.. What browsers do you plan to support as JavaScript compilation targets?.. What browsers support Dart now?.. Why was the JavaScript output for "Hello world" so big?.. How do I debug Dart code after it's been compiled to JavaScript?.. Will any valid Dart code compile to JavaScript, or are there limitations?.. Does Dart support JSON?.. Will Dart run on the server?.. Acknowledgments.. Q.. At Google we've written our share of web apps, and we've tried in many ways to make improvements to that development process, short of introducing a new language.. Now we think it's time to take that leap.. We designed Dart to be easy to write development tools for, well-suited to modern app development, and capable of high-performance implementations.. We want to.. fix ALL the things.. There's "Dart" the language, and then there's "Dart" the overall project.. The Dart.. project.. is betting that the language needs some changes, but we also want to.. improve the DOM.. and other libraries, and to improve the tools we use.. At the same time, Google is also placing bets that JavaScript.. can.. be evolved as needed, and contributing to that work.. Google wants web development to be great, and if that happens with JavaScript, we're happy.. If people like Dart and use it, then to a certain extent, yes, but isn't this true of any improvement to existing web development? Nothing is zero-effort to learn or 100% back-compatible to legacy browsers, so people use both new and old.. You might look at it this way: Google is putting significant effort behind both Dart and JavaScript, choosing to develop Dart while at the same time using JavaScript extensively, and working on JavaScript tools, implementation, and language spec.. We're doing both because we think Dart is worth it.. Server-side web programming finds room for many languages: does Python divert effort from Perl, and does Java undercut C++? Again, to a certain extent, yes they do, but people generally consider that a healthy situation, better than if we all used a single programming language.. Multiple languages have allowed for faster change than any single language has achieved through a standards process.. Furthermore, languages coexist in different niches: does Groovy really compete directly with C++? People face different engineering tradeoffs and choose different languages to meet them.. Ultimately, we think client-side developers should have this kind of flexibility.. Yes, we hope to.. Once Dart reaches a certain level of maturity and acceptance, we expect that a standards process will be the next step.. We plan to handle it like the V8 project.. We'll listen to feedback and issues, and we'll review patches from outside contributors.. A contributor with a good track record can become a committer to the repository.. Google engineers will also be working in the public repository, making visible changes.. We're taking the usual route to get to an open-standard programming language: someone creates a coherent first version, people experiment with it, and we standardize later.. The open standard web platform has been known to add other pieces this way, where standardization follows after a vendor experiment: canvas, for example.. We understand that this route raises concerns, but we think it is sometimes useful, and in particular that it is useful for programming languages, where design by committee is risky.. The most recent successful language designed by an open committee was Haskell, starting in 1990.. The most widely used was COBOL, followed by Ada.. It's not a common way to do language design.. Among dozens and dozens of major languages, six (give or take a couple of debatables) were designed this way.. (And one of those six was ALGOL-68.. ).. Bruce Johnson.. posted on the GWT blog.. (with further comments.. on Plus.. ): "Dart and GWT both share the goal of enabling structured web programming.. In fact, many of the same engineers who brought you GWT are working on Dart.. We view Dart as an ambitious evolution of GWT's mission to make web apps better for end users, and we're optimistic about its potential.. As Dart evolves and becomes ready for prime time, we anticipate working closely with the GWT developer community to explore Dart.. "Meanwhile, rest assured that GWT will continue to be a productive and reliable way to build the most ambitious web apps and even games like Angry Birds.. Key projects within Google rely on GWT every day, and we plan to continue improving (and open-sourcing) GWT based on their real-world needs.. Each approach has advantages and disadvantages, but we feel that in the context of Dart it made sense to build a language-specific VM for the following reasons:.. Google already works on a multi-language bytecode:.. LLVM bitcode in PNaCl.. Even if a bytecode VM is specialized for Dart, a language VM will be simpler and faster because it can work under stronger assumptions for instance, a structured control flow.. These assumptions make the implementation cleaner and optimizations easier.. A general-purpose bytecode VM would be even larger and slower, as it generalizes assumptions and adds functionality that for Dart is dead code: for example, multithreading with a shared heap.. No bytecode VM is truly general-purpose;  ...   and without your feature is good evidence; a sizeable codebase that shows the need is even better evidence.. Please don't be surprised if the Dart designers say "no" by default, especially for now.. It's far more painful to remove a language feature than to add it, so Dart is likely to add the most obvious features first, and then revisit the next tier later.. And there simply are more possible language features in the world that can fit into any single language without making a total hash of it.. But we do very much appreciate suggestions and evidence.. We hope you'll see our appreciation through careful design choices and fair communication about them.. That's not specified by the language, and it's left up to the compiler or editor that wants to do it.. Type inference could certainly be useful.. We want to maintain the feel of a dynamically typed language, which is familiar to web developers.. Mandatory types don't fit with that goal.. There isn't a "type system" in the traditional sense.. Our main goals for the types are to support tooling and documentation.. We want to build a pragmatic tool that helps web programmers without getting in their way.. In particular, we want our static warnings to be optimistic rather than to complain about dynamically typed code that may be valid and correctly written, such as "downcast" assignments.. Because Dart execution is always type-safe, we can let some unsound cases get through the static warnings and be caught at run time instead.. Typical object-oriented languages let you downcast, which also introduces unsoundness into the type system and may result in a runtime type error.. In Dart, we choose to allow downcasts without a syntax to mark them.. Sound types can help with performance but aren't essential.. What we need are uniform, simple semantics.. If type annotations affect the runtime, programs will change their behavior as programmers add type information, even though the logic remains unchanged.. The normal mode of development is to gradually add types for documentation and validation, and if that changes what the program does, programmers have no stable foundation to work on.. This is especially true given that types could be inaccurate.. In addition, this policy helps us and others add additional type-checking tools that implement different policies without unforeseen interactions with the runtime.. Covariant generics fit a common intuition that programmers have, and very often this intuition is correct, such as in the common "read-only" use of a generic.. Although this intuition isn't always correct, Dart doesn't need it to be.. Dart has already chosen optimistic static checking, so why not continue down that path and allow covariant uses of generics to pass static type checking?.. Where covariant generics are too optimistic, Dart's type-safe execution allows the static warnings to be optimistic without being dangerous.. Although covariance can be pessimistic too, we think it will be rare that people run into that, and and there's a simple workaround for any pessimism.. We are familiar with a variety of ways that languages try to mark or infer variance.. We don't think any of them are suitable for Dart, where we want type annotations to be optional and unobtrusive: it wouldn't fit to.. require.. marking, and we feel that variance inference systems add too much complexity for their benefit in Dart.. Again, we're trying to be pragmatic, and we think the outcome is reasonable.. If you want to experiment, we'd love for you to try Dart and give us feedback.. If your web app is something that needs to be reliable, we really recommend waiting until Dart is more mature.. We've released Dart at a very early stage, and we're likely to make breaking changes to the language.. Right now, the supported way is to port the library to Dart.. We're trying an approach using isolates: Dart code calls across an isolate boundary to JavaScript, using RPC stub code that we hope to autogenerate.. This approach has the good property that you never have multiple heaps trying to share data, and that you're not locking yourself out from running on a Dart VM.. We'll see how it works.. You could use the isolate model described in the previous question, which will encourage you to port fairly coarse chunks with narrow interfaces.. We know you might like fine-grained intercalling, but we are nervous that it would have long-term negative effects on the language and on the VM (from experience with GWT JSNI), and we would very much rather do without it.. So the.. native.. keyword is intended for use only by our core library implementations, because we want to be able to make breaking changes to the interaction between native JavaScript and generated JavaScript, breaking only our own core libraries, not the whole world.. Again, we'll see how this works.. We're currently aiming to support the following browsers:.. Internet Explorer, latest two versions that are 9 or higher.. Firefox, latest two versions that are 7 or higher.. Chrome, latest version.. Safari, latest two versions that are 5.. 1 or higher.. Opera, latest version that is 12 or higher.. That's a goal; we don't actually support all of these browsers yet.. The goal may change to be either more restrictive or more permissive.. We'll refine this further as Dart matures.. As of February 2012, no production browsers can execute Dart code unless it's first compiled to JavaScript.. However, a Chromium build (nicknamed.. Dartium.. ) is available that can execute Dart code natively.. For details on downloading and using Dartium, see.. Chromium with the Dart VM.. Dart was young.. At the launch of Dart, our initial goal was to generate functional JavaScript from Dart code.. Since the initial launch, we've created an improved compiler, dart2js, written in Dart.. This compiler aims to be compliant with the language specification, and will continue to be optimized for performance.. The dart2js compiler generates significantly smaller JavaScript output than the launch version of dartc (the original Dart-to-JavaScript compiler).. The generated JavaScript from dart2js is readable, and it's reasonable to use the browser's development tools on it.. We expect to eventually provide Source Maps output, which allows you to debug the Dart code from the JavaScript code inside of your browser's developer tools.. Yes, we intend for any valid Dart code to compile to JavaScript.. If some support is missing from one of our compilers, that's a bug (in either the compiler or the spec).. Yes, Dart libraries can parse from and stringify to JSON.. You can find such a library at.. dart/lib/json/.. We have some server code now, such as our test suites.. Have a look at the file, socket, and process APIs in.. dart/runtime/bin/.. Thanks to users who asked questions, and to many Googlers who contributed questions, answers, and improvements: Mukesh Agrawal, Lars Bak, Adam Barth, Gilad Bracha, Paul Brauner, David Carlson, Patrick Doyle, Matthias Ernst, Nicolas Geoffray, Dan Grove, William Hesse, Bruce Johnson, Seth Ladd, Patrick Linehan, Florian Loitsch, John Messerly, Srdjan Mitrovic, Anton Muhin, Bob Nystrom, Jack Palevich, David Rochberg, Matt Shulman, Joel Webber, Brian Wilkerson..

    Original link path: /support/faq.html
    Open archive

  • Title: Dart Editor | Dart: Structured web apps
    Descriptive info: You have scripting turned off.. This page will have.. Linux.. Windows.. Mac.. info mixed together unless you enable JavaScript.. Lightweight.. Open source.. Download 64-bit Dart Editor.. Download 32-bit Dart Editor.. Current version of Dart Editor:.. [calculating].. New to Dart Editor?.. Getting Started with Dart Editor.. Use IntelliJ?.. Check out JetBrains'.. Dart plugin for IntelliJ and WebStorm.. Problems?.. Troubleshooting Dart Editor.. Getting Dart Editor.. Viewing samples.. Managing the Files view.. Creating apps.. Editing apps.. Running apps.. Debugging apps.. Compiling to JavaScript.. Clearing Dart Editor settings.. Other features.. You can download Dart Editor for.. Want to live on the bleeding edge? Download the.. latest build:.. 64-bit.. 32-bit.. latest build.. Be sure to.. send feedback.. !.. for help with downloading and launching Dart Editor.. The Dart Editor download includes:.. Dart Editor.. "Dartium".. : a build of the Chromium browser that includes the Dart VM.. The default version of Dart Editor is the.. integration build.. It's automatically updated about once per week.. change log.. has a list of release dates and features.. Another option is the.. continuous build.. the latest, bleeding edge,.. untested.. version of Dart Editor.. If you use the continuous build, please update it frequently and.. about new features and bugs that you encounter.. The Welcome page of Dart Editor displays a few samples.. To open a sample and look at its source code, click the sample's image.. If you don't see the Welcome page, you probably closed it.. Get it back with.. Tools > Welcome Page.. Another way to open a sample is by opening it through the.. File.. menu.. Choose.. File > Open Folder.. , then navigate to your Dart installation directory.. Go to.. samples.. , and then open your sample's directory (for example,.. sunflower.. The Files view shows the files that implement the libraries included in Dart, as well as all the apps that you create or open.. Adding apps.. Here's how to open an app, which makes it appear in your Files view:.. Go to the.. menu, and choose.. Open Folder.. Or use the keyboard shortcut (.. Ctl+O.. or, on Mac,.. Cmd+O.. Select the directory that contains the app's files, and click.. Open.. The directory and all its files appear in the Files view.. Removing apps.. You can remove an app from the Files view, either with or without deleting its files.. To hide the app but keep it in your file system, right-click the directory in the Files view (on the Mac: Ctl+click), and choose.. Close Folder.. To delete the app and its files permanently, right-click (or Ctl+click) the directory and choose.. Delete.. It's easy to create a simple web or command-line app from scratch:.. Click the New Application button.. (at the upper left of Dart Editor).. Alternatively, choose.. File > New Application.. from the Dart Editor menu.. A dialog appears.. Type in a name for your application for example,.. HelloWorld.. If you don't like the default directory, type in a new location or browse to choose the location.. If you're creating a web app, select.. Generate content for a basic web app.. Then click.. Finish.. to create the initial files for the app.. A default Dart file appears in the Edit view, and its directory appears in the Files view.. Your Dart Editor window should look something like this:.. Dart Editor provides the basic editing functionality you'd expect, plus features such as Dart code completion, API browsing, support for refactoring, and the ability to search multiple files.. Using autocomplete.. Autocomplete suggestions look something like this:.. The autocomplete suggestions appear when you either:.. Type a class, interface, or variable name, and then type a period.. For example, type.. and pause a moment.. Once the suggestions appear, continue typing to pare down the list.. Type.. Ctl+Space.. Str.. , then Ctl+Space to see a list of classes and interfaces that start with "Str".. When the suggestions come up, you can click, type, or use the arrow keys to select the one you want.. Press Enter or Return to choose a suggestion, or Esc to dismiss the panel.. Browsing APIs.. With Dart Editor you can easily find where APIs are declared.. You can also outline the contents of a Dart file.. Finding where an API is declared.. Use this feature to go to  ...   least one configuration for each additional browser.. You can specify the following for command-line apps:.. dart file to execute.. Arguments to pass to the app.. Checked mode.. Heap size.. Running in production mode.. By default, apps run in checked mode.. To run in production mode instead, disable checked mode in your app's launch configuration:.. Run your app at least once, so that it has a launch configuration.. , or click the little arrow to the right of the Run button.. In the Manage Launches dialog, find a launch configuration for your app.. Click it if it isn't already selected.. Unselect.. Run in checked mode.. Click.. Apply.. to save your change, or.. Run.. to save it and run your app.. For details about checked mode and production mode, see.. in the language tour.. Specifying a browser.. To specify the browser in which the your app runs:.. The Manage Launches dialog appears.. On the left side of the dialog is a list of all launch configurations that you've created or that were automatically created for you.. On the right is information about the currently selected launch configuration.. In the Manage Launches dialog, click the Create new launch button.. , and choose.. Dart JavaScript launch.. Enter configuration information:.. Give the configuration a name that identifies the app, the browser, and anything else important.. HelloWeb.. html in Firefox.. Specify the HTML file or URL to open.. /HelloWeb/HelloWeb.. html.. Unless you want to use the default system browser, unselect "Use default system browser" and specify the location of the browser you want to use.. /Applications/Firefox.. app.. to save your changes, or.. to save your changes and launch the app.. Now that you've set up the launch, you can choose it any time from the Run button.. Your app will be automatically compiled to JavaScript each time you run it.. You can debug both command-line and web apps with Dart Editor.. Debugging must be enabled in your launch configuration (which it is, by default).. Note:.. Command-line debugging is currently supported for Mac and Linux only.. We expect to support Windows as well.. Some tips for debugging:.. Set breakpoints by double-clicking in the left margin of the Edit view.. Use the Debugger view to view your app's state and control its execution.. By default, the Debugger view is to the right of the Edit view.. To see the values of variables, mouse over the variable or look in the Debugging view's Call Stack.. Because everything in Dart is an object and operators are really methods, you'll probably use Step Return (F7) more than you'd expect to climb out of Dart libraries.. To debug web apps, you use Dart Editor with Dartium.. While you're debugging, Dart Editor takes the place of the Dartium console.. For example, Dart Editor displays the output of print() statements.. You might not need to do anything to compile your code to JavaScript.. When you run an app using a.. launch configuration that specifies a browser.. , Dart Editor automatically compiles the app to JavaScript before executing it in the browser.. However, you can also compile Dart code to JavaScript without running it.. Just choose.. Tools > Generate JavaScript.. Dart Editor settings are in a platform-dependent directory, so you don't lose them when you update Dart Editor.. If your settings become corrupted or you want to see the new user experience, delete the settings directory.. The following table shows where Dart Editor settings are saved.. Platform.. Location of settings.. Windows.. user's home directory.. \DartEditor.. Linux.. $HOME/.. dartEditor.. Mac.. $HOME/Library/Application Support/DartEditor.. Dart Editor has many additional features, including customization and keyboard alternatives.. Customizing Dart Editor.. You can customize the editor's font, margins, key bindings, and more using the Preferences dialog.. To bring up the dialog, choose.. Tools > Preferences.. (or on Mac:.. Dart Editor > Preferences.. You can also customize which views you see in Dart Editor, as well as their size and position.. To add views, use the.. Tools.. To remove a view, click its.. X.. To move a view, drag its tab to a different position, either within or outside of the Dart Editor window.. To resize a view, drag its edges.. Keyboard alternatives.. To get a list of all keyboard alternatives, choose.. Help > Key Assist..

    Original link path: /docs/editor/
    Open archive

  • Title: Chromium with the Dart VM | Dart: Structured web apps
    Descriptive info: Chromium with the Dart VM.. This page tells you how to get and use a Chromium-based browser (nicknamed.. ) that includes the Dart virtual machine (VM).. This browser can execute Dart web apps directly, so you don't have to compile your code to JavaScript until you're ready to test on other browsers.. Dartium is available for.. Warning:.. This browser is a technical preview, and it might have security and stability issues.. Do not use Dartium as your primary browser!.. Downloading and installing the browser.. Launching the browser.. Filing bugs.. Linking to Dart source.. Detecting Dart support.. Launching from the command line.. Downloading and installing the browser.. If you have an up-to-date version of.. , you already have Dartium.. If you don't have Dart Editor or want a different version of Dartium, you can download it separately:.. Dartium (Windows).. Dartium (Mac).. Dartium (Linux).. The Dartium binary.. will expire.. after a few days.. When that happens, you'll need to download a new copy if you want to continue using Dartium.. You don't usually need to do anything special to install Dartium: just unarchive the ZIP file.. If you want Dart Editor to launch a particular copy of Dartium, then put that copy inside the.. dart-sdk.. directory of your.. Dart Editor installation directory.. , replacing the original copy of Chromium.. Launching the browser.. To launch Dartium, navigate to its directory in your finder, and double-click the Chromium executable file.. Or use.. or  ...   the Dart VM and handles non-Dart browsers --.. text/javascript.. http://dart.. googlecode.. com/svn/trunk/dart/client/dart.. js.. /body.. /html.. The Dart Editor automatically adds both the.. script tag and the bootstrap JavaScript tag into the project's main HTML file.. Detecting Dart support.. The above example uses a bootstrap script that takes care of turning on the Dart VM, as well as compatibility with non-Dart browsers.. Instead of using the.. dart.. script, you can manually include the necessary JavaScript code.. To start the Dart VM, look for the function.. webkitStartDart.. on the window.. navigator object.. For example:.. navigator.. // No native Dart support.. window.. addEventListener.. DOMContentLoaded.. Fall back to compiled JS.. },.. ()).. This build has expired.. Please download a new Dartium at http://www.. dartlang.. org/dartium/index.. Launching from the command line.. Because Dartium is based on Chromium, all.. Chromium flags.. should work.. In some cases, you might want to specify Dart-specific flags so that you can tweak the embedded Dart VM's behavior.. For example, while developing your web app, you might want the VM to perform as many checks as possible.. To achieve that, you can enable checked mode (the VM's --enable_type_checks flag) and assertion checks (--enable_asserts flag).. On Linux, you can specify flags by starting Dartium as follows:.. DART_FLAGS.. --enable_type_checks --enable_asserts.. PATH/chrome.. On the Mac:.. \.. PATH/Chromium.. app/Contents/MacOS/Chromium.. Or (also on the Mac):.. DART_FLAG.. open PATH/Chromium.. You can see the command-line flags and executable path of your current Chromium-based browser by going to.. chrome://version..

    Original link path: /dartium/
    Open archive

  • Title: Getting Started with the SDK | Dart: Structured web apps
    Descriptive info: Getting Started with the SDK.. This page tells you how to find and use prerelease versions of the Dart SDK on.. (These instructions are available for.. Getting the SDK.. SDK contents.. Getting the SDK.. , you already have the SDK.. Look for a dart-sdk directory inside of the Dart Editor directory.. If you don't have Dart Editor or want a different version of the SDK, download the ZIP file for your platform's SDK:.. 64-bit Dart SDK (Windows).. 32-bit Dart SDK (Windows).. 64-bit Dart SDK (Mac)..  ...   latest, untested build of the.. Windows 64 bit SDK.. Windows 32 bit SDK.. macos.. Mac 64 bit SDK.. Mac 32 bit SDK.. linux.. Linux 64 bit SDK.. Linux 32 bit SDK.. These continuous builds usually are updated daily.. After you download and unpack the SDK, you'll have a directory named.. You'll see a.. bin.. directory for the command-line tools, and a.. lib.. directory for the Dart libraries.. The SDK includes the.. Dart libraries.. and the following command-line tools:.. Dart-to-JavaScript compiler.. (dart2js).. (dart).. Dart package manager.. (pub)..

    Original link path: /docs/sdk/
    Open archive

  • Title: dart2js: The Dart-to-JavaScript Compiler | Dart: Structured web apps
    Descriptive info: dart2js: The Dart-to-JavaScript Compiler.. This page tells you how to use the.. dart2js.. tool to compile Dart code to JavaScript.. Dart Editor uses dart2js behind the scenes whenever.. Dart Editor compiles to JavaScript.. bin/dart2js.. executable is in the.. You can either.. download the SDK separately.. or get it as part of the.. Dart Editor  ...   Dart file to JavaScript:.. $DART_SDK.. /bin/dart2js test.. This command produces a.. file that contains the JavaScript equivalent of your Dart code.. Options.. Common command-line options for dart2js include:.. -o.. file.. Generate the output into.. -c.. Insert runtime type checks and enable assertions (checked mode).. -h.. Display this message (add -v for information about all options)..

    Original link path: /docs/dart2js/
    Open archive

  • Archived pages: 96