Dart Programing Language For Beginners
Dart Programing Language For Beginners
Dart Programing Language For Beginners
dart
Table of Contents
About 1
Remarks 2
Links 2
Documentation 2
FAQ 3
Versions 3
Examples 5
Installation or Setup 5
Manual install 5
Hello, World! 5
Http Request 6
Html 6
Dart 6
Example 6
Examples 8
Chapter 3: Classes 10
Examples 10
Creating a class 10
Members 10
Constructors 11
Chapter 4: Collections 13
Examples 13
Filter a list 14
Chapter 5: Comments 16
Syntax 16
Remarks 16
Examples 16
Multi-Line Comment 16
Examples 18
If Else 18
While Loop 18
For Loop 19
Switch Case 19
Examples 21
JSON 21
Introduction 22
Examples 22
Examples 24
Examples 25
Basic usage 25
Remarks 26
Examples 26
Custom exception 26
Remarks 27
Examples 27
Function scoping 27
Remarks 29
Examples 29
Using libraries 29
Introduction 32
Examples 32
Remarks 33
Examples 33
pub build 33
pub serve 33
Syntax 34
Parameters 34
Remarks 34
Examples 34
Examples 35
Valid strings 35
Credits 37
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: dart
It is an unofficial and free dart ebook created for educational purposes. All the content is extracted
from Stack Overflow Documentation, which is written by many hardworking individuals at Stack
Overflow. It is neither affiliated with Stack Overflow nor official dart.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Dart targets a wide range of development scenarios, from a one-person project without much
structure to a large-scale project needing formal types in the code to state programmer intent.
To support this wide range of projects, Dart provides the following features and tools:
• Optional types: this means you can start coding without types and add them later as
needed.
• Isolates: concurrent programming on server and client
• Easy DOM access: using CSS selectors (the same way that jQuery does it)
• Dart IDE Tools: Dart plugins exist for many commonly used IDEs, Ex: WebStorm.
• Dartium: a build of the Chromium Web Browser with a built-in Dart Virtual Machine
Links
• The Dart Homepage
• Official Dart News & Updates
• The Dartosphere - A collection of recent Dart blog posts
• Dartisans Dartisans community on Google+
• Dart Web Development - Google Groups Page
• Dart Language Misc - Google Groups Page
• DartLang sub-Reddit
Documentation
• Tour of the Dart Language
• Tour of the Dart Libraries
• Dart Code samples
• Dart API Reference
https://riptutorial.com/ 2
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
FAQ
• Frequently Asked Questions
Versions
1.22.1 2017-02-22
1.22.0 2017-02-14
1.21.1 2016-01-13
1.21.0 2016-12-07
1.20.1 2016-10-13
1.20.0 2016-10-11
1.19.1 2016-09-07
1.19.0 2016-08-26
1.18.1 2016-08-02
1.18.0 2016-07-27
1.17.1 2016-06-10
1.17.0 2016-06-06
1.16.1 2016-05-23
1.16.0 2016-04-26
1.15.0 2016-03-09
1.14.2 2016-02-09
1.14.1 2016-02-03
1.14.0 2016-01-28
1.13.2 2016-01-05
1.13.1 2015-12-17
1.13.0 2015-11-18
https://riptutorial.com/ 3
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
1.12.2 2015-10-21
1.12.1 2015-09-08
1.12.0 2015-08-31
1.11.3 2015-08-03
1.11.1 2015-07-02
1.11.0 2015-06-24
1.10.1 2015-05-11
1.10.0 2015-04-24
1.9.3 2015-04-13
1.9.1 2015-03-25
1.8.5 2015-01-13
1.8.3 2014-12-01
1.8.0 2014-11-27
1.7.2 2014-10-14
1.6.0 2014-08-27
1.5.8 2014-07-29
1.5.3 2014-07-03
1.5.2 2014-07-02
1.5.1 2014-06-24
1.4.3 2014-06-16
1.4.2 2014-05-27
1.4.0 2014-05-20
1.3.6 2014-04-30
1.3.3 2014-04-16
1.3.0 2014-04-08
https://riptutorial.com/ 4
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
1.2.0 2014-02-25
1.1.3 2014-02-06
1.1.1 2014-01-15
1.0.0.10_r30798 2013-12-02
1.0.0.3_r30188 2013-11-12
0.8.10.10_r30107 2013-11-08
0.8.10.6_r30036 2013-11-07
0.8.10.3_r29803 2013-11-04
Examples
Installation or Setup
The Dart SDK includes everything you need to write and run Dart code: VM, libraries, analyzer,
package manager, doc generator, formatter, debugger, and more. If you are doing web
development, you will also need Dartium.
Manual install
You can also manually install any version of the SDK.
Hello, World!
void main() {
print('Hello, World!');
}
In the terminal, navigate to the directory containing the file hello_world.dart and type the following:
dart hello_world.dart
https://riptutorial.com/ 5
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Http Request
Html
<img id="cats"></img>
Dart
import 'dart:html';
/// Stores the image in [blob] in the [ImageElement] of the given [selector].
void setImage(selector, blob) {
FileReader reader = new FileReader();
reader.onLoad.listen((fe) {
ImageElement image = document.querySelector(selector);
image.src = reader.result;
});
reader.readAsDataUrl(blob);
}
main() async {
var url = "https://upload.wikimedia.org/wikipedia/commons/2/28/Tortoiseshell_she-cat.JPG";
Example
see Example on https://dartpad.dartlang.org/a0e092983f63a40b0b716989cac6969a
void main() {
var cat = new Cat();
class Cat {
bool _isHungry = true;
https://riptutorial.com/ 6
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Dart class getters and setters allow APIs to encapsulate object state changes.
https://riptutorial.com/ 7
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Future<Results> costlyQuery() {
var completer = new Completer();
import 'dart:async';
var n = 100000000;
https://riptutorial.com/ 8
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Dart has a robust async library, with Future, Stream, and more. However, sometimes you might
run into an asynchronous API that uses callbacks instead of Futures. To bridge the gap between
callbacks and Futures, Dart offers the Completer class. You can use a Completer to convert a
callback into a Future.
Completers are great for bridging a callback-based API with a Future-based API. For example,
suppose your database driver doesn't use Futures, but you need to return a Future. Try this code:
Future doStuff() {
Completer completer = new Completer();
runDatabaseQuery(sql, (results) {
completer.complete(results);
});
return completer.future;
}
If you are using an API that already returns a Future, you do not need to use a Completer.
https://riptutorial.com/ 9
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Chapter 3: Classes
Examples
Creating a class
class InputField {
int maxLength;
String name;
}
The class can be instantiated using the new keyword after which the field values will be null by
default.
Members
Instance variables can be declared with/without type annotations, and optionally initialized.
Uninitialised members have the value of null, unless set to another value by the constructor.
class Foo {
var member1;
int member2;
String member3 = "Hello world!";
}
class Bar {
static var member4;
static String member5;
static int member6 = 42;
}
If a method takes no arguments, is fast, returns a value, and doesn't have visible side-effects, then
https://riptutorial.com/ 10
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
class Foo {
String get bar {
var result;
// ...
return result;
}
}
Getters never take arguments, so the parentheses for the (empty) parameter list are omitted both
for declaring getters, as above, and for calling them, like so:
main() {
var foo = new Foo();
print(foo.bar); // prints "bar"
}
There are also setter methods, which must take exactly one argument:
class Foo {
String _bar;
main() {
var foo = new Foo();
foo.bar = "this is calling a setter method";
}
Constructors
class Person {
String name;
String gender;
int age;
The example above is a simpler, better way of defining the constructor than the following way,
which is also possible:
https://riptutorial.com/ 11
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
class Person {
String name;
String gender;
int age;
https://riptutorial.com/ 12
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Chapter 4: Collections
Examples
Creating a new List
If you prefer stronger typing, you can also supply a type parameter in one of the following ways:
For creating a small growable list, either empty or containing some known initial values, the literal
form is preferred. There are specialized constructors for other kinds of lists:
https://riptutorial.com/ 13
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Types for the key and value can also be defined using generics:
var map = {
"key1": "value1",
"key2": "value2"
};
All collection objects contain a map method that takes a Function as an argument, which must take
a single argument. This returns an Iterable backed by the collection. When the Iterable is
iterated, each step calls the function with a new element of the collection, and the result of the call
becomes the next element of the iteration.
You can turn an Iterable into a collection again by using the Iterable.toSet() or Iterable.toList()
methods, or by using a collection constructor which takes an iterable like Queue.from or List.from.
Example:
main() {
var cats = [
'Abyssinian',
'Scottish Fold',
'Domestic Shorthair'
];
var catsInReverse =
cats.map((String cat) {
return new String.fromCharCodes(cat.codeUnits.reversed);
})
.toList(); // [nainissybA, dloF hsittocS, riahtrohS citsemoD]
print(catsInReverse);
}
Filter a list
Of course you can use some AND or OR operators in your where clause.
https://riptutorial.com/ 14
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
https://riptutorial.com/ 15
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Chapter 5: Comments
Syntax
• // Single-line comment
• /* Multi-line/In-line comment */
• /// Dartdoc comment
Remarks
It is good practice to add comments to your code to explain why something is done or to explain
what something does. This helps any future readers of your code to more easily understand your
code.
Examples
End of Line Comment
Multi-Line Comment
void main() {
for (int i = 0; i < 5; i++) {
/* This is commented, and
will not affect code */
print('hello ${i + 1}');
}
}
Using a doc comment instead of a regular comment enables dartdoc to find it and generate
documentation for it.
https://riptutorial.com/ 16
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
You are allowed to use most markdown formatting in your doc comments and dartdoc will process
it accordingly using the markdown package.
https://riptutorial.com/ 17
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
While Loop
while(peopleAreClapping()) {
playSongs();
}
and:
do {
processRequest();
} while(stillRunning());
while (true) {
if (shutDownRequested()) break;
processIncomingRequests();
}
https://riptutorial.com/ 18
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
For Loop
and:
The for-in loop is convenient when simply iterating over an Iterable collection. There is also a
forEach method that you can call on Iterable objects that behaves like for-in:
flybyObjects.forEach(print);
Switch Case
Dart has a switch case which can be used instead of long if-else statements:
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'OPEN':
executeOpen();
break;
case 'APPROVED':
executeApproved();
break;
case 'UNSURE':
// missing break statement means this case will fall through
// to the next statement, in this case the default case
default:
executeUnknown();
}
You can only compare integer, string, or compile-time constants. The compared objects must be
instances of the same class (and not of any of its subtypes), and the class must not override ==.
https://riptutorial.com/ 19
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
One surprising aspect of switch in Dart is that non-empty case clauses must end with break, or
less commonly, continue, throw, or return. That is, non-empty case clauses cannot fall through.
You must explicitly end a non-empty case clause, usually with a break. You will get a static
warning if you omit break, continue, throw, or return, and the code will error at that location at
runtime.
If you want fall-through in a non-empty case, you can use continue and a label:
https://riptutorial.com/ 20
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
import 'dart:convert';
void main() {
var jsonString = """
{
"cats": {
"abysinnian": {
"origin": "Burma",
"behavior": "playful"
}
}
}
""";
print(obj['cats']['abysinnian']['behavior']); // playful
}
https://riptutorial.com/ 21
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
The interoperability is achieved by using the js library to create Dart stubs. These stubs describe
the interface we'd like to have with the underlying JavaScript code. At runtime calling the Dart stub
will invoke the JavaScript code.
Examples
Calling a global function
Suppose we'd like to invoke the JavaScript function JSON.stringify which receives an object,
encodes it into a JSON string and returns it.
All we'd have to do is write the function signature, mark it as external and annotate it with the @JS
annotation:
@JS("JSON.stringify")
external String stringify(obj);
The @JS annotation will be used from here on out to mark Dart classes that we'd like to use in
JavaScript as well.
Suppose we'd like to wrap the Google Maps JavaScript API google.maps:
@JS('google.maps')
library maps;
import "package:js/js.dart";
@JS()
class Map {
external Map(Location location);
external Location getLocation();
}
We now have the Map Dart class which corresponds to the JavaScript google.maps.Map class.
Note that you don't have to name your Dart class the same as the JavaScript class:
@JS("LatLng")
https://riptutorial.com/ 22
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
class Location {
external Location(num lat, num lng);
}
// JavaScript
printOptions({responsive: true});
Unfortunately we cannot pass Dart Map objects to JavaScript in these cases.
What we have to do is create a Dart object that represents the object literal and contains all of its
fields:
// Dart
@JS()
@anonymous
class Options {
external bool get responsive;
Note that the Options Dart class doesn't correspond to any JavaScript class. As such we must
mark it with the @anonymous annotation.
Now we can create a stub for the original printOptions function and call it with a new Options
object:
// Dart
@JS()
external printOptions(Options options);
https://riptutorial.com/ 23
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
https://riptutorial.com/ 24
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
enum Fruit {
apple, banana
}
main() {
var a = Fruit.apple;
switch (a) {
case Fruit.apple:
print('it is an apple');
break;
}
https://riptutorial.com/ 25
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
In contrast to Java, all of Dart’s exceptions are unchecked exceptions. Methods do not declare
which exceptions they might throw, and you are not required to catch any exceptions.
Dart provides Exception and Error types, as well as numerous predefined subtypes. You can, of
course, define your own exceptions. However, Dart programs can throw any non-null object—not
just Exception and Error objects—as an exception.
Examples
Custom exception
void main() {
try {
throwException();
} on CustomException {
print("custom exception is been obtained");
}
}
throwException() {
throw new CustomException('This is my first custom exception');
}
https://riptutorial.com/ 26
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Examples
Functions with named parameters
When calling a function, you can specify named parameters using paramName: value
Function scoping
Dart functions may also be declared anonymously or nested. For example, to create a nested
function, just open a new function block within an existing function block
void outerFunction() {
bool innerFunction() {
/// Does stuff
}
}
The function innerFunction may now be used inside, and only inside, outerFunction. No other other
functions has access to it.
Functions in Dart may also be declared anonymously, which is commonly used as function
arguments. A common example is the sort method of List object. This method takes an optional
argument with the following signature:
int compare(E a, E b)
The documentation states that the function must return 0 if the a and b are equal. It returns -1 if a <
b and 1 if a > b.
https://riptutorial.com/ 27
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
numbers.sort((int a, int b) {
if(a == b) {
return 0;
} else if (a < b) {
return -1;
} else {
return 1;
}
});
numbers.sort(intSorter);
https://riptutorial.com/ 28
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Examples
Using libraries
Use import to specify how a namespace from one library is used in the scope of another library.
import 'dart:html';
The only required argument to import 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. The package: scheme specifies libraries provided by a package manager such as the pub
tool. For example:
import 'dart:io';
import 'package:mylib/mylib.dart';
import 'package:utils/utils.dart';
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.
If you for example have class A in a separate library file (eg, other.dart), such as:
library other;
class A {
int _private = 0;
testA() {
print('int value: $_private'); // 0
_private = 5;
print('int value: $_private'); // 5
}
}
https://riptutorial.com/ 29
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
import 'other.dart';
void main() {
var b = new B();
b.testB();
}
class B extends A {
String _private;
testB() {
_private = 'Hello';
print('String value: $_private'); // Hello
testA();
print('String value: $_private'); // Hello
}
}
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.
If you want to use only part of a library, you can selectively import the library. For example:
Deferred loading (also called lazy loading) allows an application to load a library on demand, if and
when it’s needed. To lazily load a library, you must first import it using deferred as.
https://riptutorial.com/ 30
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
When you need the library, invoke loadLibrary() using the library’s identifier.
greet() async {
await hello.loadLibrary();
hello.printGreeting();
}
In the preceding code, the await keyword pauses execution until the library is loaded. For more
information about async and await, see more examples here asynchrony support or visit the
asynchrony support part of the language tour.
https://riptutorial.com/ 31
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Examples
Filtering a list of integers
[-1, 0, 2, 4, 7, 9].where((x) => x > 2) --> [4, 7, 9]
https://riptutorial.com/ 32
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Examples
pub build
Use pub build when you’re ready to deploy your web app. When you run pub build, it generates
the assets for the current package and all of its dependencies, putting them into new directory
named build.
To use pub build, just run it in your package’s root directory. For example:
$ cd ~/dart/helloworld
$ pub build
Building helloworld......
Built 5 files!
pub serve
This command starts up a development server, or dev server, for your Dart web app. The dev
server is an HTTP server on localhost that serves up your web app’s assets.
Start the dev server from the directory that contains your web app’s pubspec.yaml file:
$ cd ~/dart/helloworld
$ pub serve
Serving helloworld on http://localhost:8080
https://riptutorial.com/ 33
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Parameters
Parameter Details
{bool
caseSensitive} If the expression is case sensitive
Remarks
Dart regular expressions have the same syntax and semantics as JavaScript regular expressions.
See http://ecma-international.org/ecma-262/5.1/#sec-15.10 for the specification of JavaScript
regular expressions.
This means that any JavaScript resource you find about Regular Expressions online applies to
dart.
Examples
Create and use a Regular Expression
It's a good idea to use "raw strings" (prefix with r) when writing regular expressions so you can
use unescaped backslashes in your expression.
https://riptutorial.com/ 34
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
You can use ${} to interpolate the value of Dart expressions within strings. The curly braces can
be omitted when evaluating identifiers:
Valid strings
A string can be either single or multiline. Single line strings are written using matching single or
double quotes, and multiline strings are written using triple quotes. The following are all valid Dart
strings:
'Single quotes';
"Double quotes";
'Double quotes in "single" quotes';
"Single quotes in 'double' quotes";
'''A
multiline
string''';
"""
Another
multiline
string""";
sb.write("Use a StringBuffer");
https://riptutorial.com/ 35
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
sb
..write("Use a StringBuffer")
..writeAll(["for ", "efficient ", "string ", "creation "])
..write("if you are ")
..write("building lots of strings");
print(fullString);
// Use a StringBufferfor efficient string creation if you are building lots of strings
https://riptutorial.com/ 36
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)
lOMoARcPSD|25360471
Credits
S.
Chapters Contributors
No
Getting started with 4444, Challe, Community, Damon, Florian Loitsch, Gomiero,
1
dart Kleak, losnake, martin, Raph, Timothy C. Quinn
Asynchronous
2 Challe, Damon, Ray Hulha, Zied Hamdi
Programming
5 Comments Challe
Dart-JavaScript
8 Meshulam Silk
interoperability
10 Enums Challe
11 Exceptions Challe
15 Pub Challe
17 Strings Challe
https://riptutorial.com/ 37
Downloaded by Pinky Rose (pinkyrose512015@gmail.com)