Paramètres
Paramètres optionnels nommés
// Affecte les flags bold et hidden à leur valeurs.
enableFlags({bool bold, bool hidden}) {
// ...
}
enableFlags(bold: true, hidden: false);
enableFlags(hidden: false, bold: true);
enableFlags(hidden : true);
enableFlags();
Paramètres optionnels positionnés
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
say('Bob', 'Howdy');
// 'Bob says Howdy'
say('Bob', 'Howdy', 'smoke signal');
// 'Bob says Howdy with a smoke signal'
Classes
Ma 1ère classe
class MaClasse {
}
var classe = new MaSuperClasse();
MaSuperClasse unAutreClasse = new MaSuperClasse();
Classe avec getter/setter
class Person {
// Visibilité restreinte par le _
String _name;
String get name => _name;
set name(val) => _name = val;
}
var p = new Person();
p.name = "John"; // Set
var name = p.name; // Get
Classe complète
import 'dart:math';
class Point {
final int x, y;
Point(this.x, this.y);
num distanceTo(Point other) {
var dx = x - other.x;
var dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
String toString() => "($x, $y)";
}
var p = new Point(2, 3);
print(p);// Affiche '(2, 3)'
var x = p.x;
var distance = p.distanceTo(new Point(5, 5));
Héritage
class Person {
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
// Person n'a pas de constructeur par défaut
// Il faut appeler super.fromJson(data).
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
Implémentation
// Person est une interface implicite contient greet().
class Person {
// Dans l'interface mais visible dans la bibliothèque
final _name;
// Pas dans l'interface car c'est une constructeur
Person(this._name);
// Méthode de l'interface
String greet(who) => 'Hello, $who. I am $_name.';
}
// Une implémentation de Person.
class Imposter implements Person {
// On le définit mais on ne l'utilise pas
final _name = "";
String greet(who) => 'Hi $who. Do you know who I am?';
}
Mixin
// Un mixin doit
// étendre Object, ne pas avoir de constructeur, pas d'appel à super
abstract class Musical {
bool canPlayPiano = false;
bool canCompose = false;
bool canConduct = false;
void entertainMe() {
//
}
}
class Musician extends Performer with Musical {
Musician(String musicianName) {
name = musicianName;
canConduct = true;
}
}
Constructeurs
Constructeur nommé
import 'dart:math';
class Point {
num x, y;
Point(this.x, this.y);
Point.zero() : x = 0, y = 0;
Point.polar(num theta, num radius) {
x = cos(theta) * radius;
y = sin(theta) * radius;
}
}
Point p1 = new Point.zero();
Point p2 = new Point.polar(0, 1);
Factory
class Logger {
final String name;
bool mute = false;
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) => _cache.putIfAbsent(name, () =>
new Logger._internal(name));
Logger._internal(this.name);
}
Logger logger = new Logger("foo");
Collections
List
// Creation de listes
var vegetables = [] // == new List();
var fruits = ['apples', 'oranges'];
// Ajout d'éléments
fruits.add('kiwis');
fruits.addAll(['grapes', 'bananas']);
assert(fruits.length == 5);
// Tri
fruits.sort();
assert(fruits[0] == 'apples');
Map
var gifts = {
// Keys Values
'first' : 'partridge',
'second' : 'turtledoves',
'fifth' : 'golden rings'
};
gifts['fourth'] = 'calling birds'; // Add a key-value pair
assert(gifts['first'] == 'partridge')
assert(gifts.length == 4);
var keys = gifts.keys;
var values = gifts.values;
Set
// Création
var ingredients = new Set();
ingredients.addAll(['gold', 'titanium', 'xenon']);
// Intersection
var nobleGases = new Set.from(['xenon', 'argon']);
var intersection = ingredients.intersection(nobleGases);
assert(intersection.length == 1);
assert(intersection.contains('xenon'));
Lamdba
var teas = ['green', 'black', 'chamomile', 'earl grey'];
// Affichage en majuscule
var loudTeas = teas.map((tea) => tea.toUpperCase());
loudTeas.forEach(print);
// La camomille n'est pas caéfinée.
bool isDecaffeinated(String teaName) => teaName == 'chamomile';
// Filtrage
var decaffeinatedTeas = teas.where(isDecaffeinated);
// Construction map
var decaffeinatedTeasMap =
new Map.fromIterable(teas, value: isDecaffeinated);
Outils
Bibliothèques
Interne |
dart:io |
Entrée/Sortie système |
dart:math |
Calcul, génération aléatoire, ... |
dart:convert |
Codec de convertion (JSon, ... ) |
dart:html |
Manipulation DOM |
Externe |
unittest |
Tests unitaires |
Polymer |
Web components |
Déclaration librairies/Import
library bestWebApp;
part 'src/crazyImpl.dart';
part 'src/wonderfullUI.dart';
import 'dart:html';
import 'package:polymer/polymer.dart';
// crazyImpl.dart
part of bestWebApp;
Pub
pubspec.yaml
name: my_app
dependencies:
polymer: ">=0.9.5 <0.10.0"
dev_dependencies:
unittest: any
transformers:
- polymer:
entry_points: web/index.html
pub get
pub build
Test
import 'package:unittest/unittest.dart';
main(){
test('Un test simple', () => expect(2+2, 4));
group('Test plus complexe', () {
setUp(() {/*...*/});
tearDown(() {/*...*/});
test('Test complexe 1', () {/*...*/});
test('Test complexe 2', () {/*...*/});
});
}
unittest-suite-wait-for-done
PASS: Un test simple
PASS: Test plus complexe Test complexe 1
PASS: Test plus complexe Test complexe 2
All 3 tests passed.
unittest-suite-success
Fondation
Custom Elements
<x-click-counter></x-click-counter>
<element name="x-click-counter">
<template>
<style>
/* Css */
</style>
<-- Html -->
</template>
<-- Code Dart -->
<script src="click_counter.dart"></script>
</element>
HTML Template
<template id="monSuperTemplate">
<div class="super-style" >
</div>
<!-- Plein de html -->
</template>
<template if="{{maCondition}}">
<template repeat="{{maList}}">
Shadow DOM
<video controls src="/ma/super/video"></video>
<video controls="" height="300" src="/ma/super/video">
#shadow-root
<div>
<div>
<div>
<input type="button">
<input type="range" precision="float" max="596.48">
<div style="display: none;">0:00</div><div>9:56</div>
<input type="button">
<input type="range" precision="float" max="1" style="">
<input type="button" style="display: none;">
<input type="button" style="">
</div>
</div>
</div>
</video>
HTML Import
<head>
<!-- Plein de déclaration -->
<link rel="import" href="/components/click_counter.html">
</head>
Observer
<div>
{{name}}
</div>
@observable String name;