Skip to content

Instantly share code, notes, and snippets.

@lfo
Last active August 29, 2015 13:55
Show Gist options
  • Save lfo/8750044 to your computer and use it in GitHub Desktop.
Save lfo/8750044 to your computer and use it in GitHub Desktop.
Gist comprenant le code dart des slides
import 'dart:convert' show JSON;
import 'dart:io';
import 'dart:async';
/////////////////////////////////////////////////////////////
// Définition d’une fonction.
printNumber(num aNumber) {
print('The number is $aNumber.'); // Écrit dans la console.
}
// Point d’entrée de l’application. C’est ici que ça démarre
main() {
var number = 42; // Déclare et initialise une variable.
printNumber(number); // Appelle une fonction.
testClosure2();
}
////////////////////////////////////////////////////////////
void variables() {
var name = 'Bob';
assert(name is String); // name : nom de la variable initialisé avec la valeur “Bob”
var name2;
assert(name2 is! String); // typage dynamique, impossible de dire le type de name2
int lineCount;
assert(lineCount == null);
// tous les objets sont initialisés à null (même les nombres, pas de type primitif)
}
////////////////////////////////////////////////////////////
void finalAndConsts() {
final name = "Laurent";
//name = "Vincent"; // Si décommenté, erreur à l'exécution.
// Une variable final est initialisée de manière lazy. Démarrage rapide
const bar = 1e5; // 100 000 pascal
const atmosphere = 1.01325 * bar;
// const évalué à la compilation
}
////////////////////////////////////////////////////////////
void numbers() {
int x = 1;
int hex = 0xDEADBEEF;
double bigDouble = 2e63;
int bigInt = 2e63; // un int est sur probablement sur 53 bits, un double 64 bits.
}
////////////////////////////////////////////////////////////
void strings() {
String firstName = "Laurent";
String lastName = "Forêt";
print("$firstName $lastName"); // interpollation plus rapide que +.
// En java : System.out.println(String.format("%s %s", firstName, lastName));
}
void booleans() {
bool soTrue = true;
assert(soTrue is bool);
var soFalse = false;
assert(soFalse is bool);
var name = 'Bob';
if (name) {
print('You have a name!'); // Prints in JavaScript, not in Dart (name != true)
}
}
////////////////////////////////////////////////////////////names
void lists() {
var list = [1,2,3];
assert(list.length == 3);
assert(list[1] == 2);
List oldFashionList = new List();
oldFashionList.add(1); oldFashionList.add(2); // etc…
List coolFeatureList = new List() // utilisons la cascade de méthode
..add(1) // plus besoin de pattern builder.
..add(2);
}
/////////////////////////////////////////////////////////////
void maps() {
var gifts = {
// Keys Values
'first' : 'partridge',
'second' : 'turtledoves',
};
gifts["fifth"] = 'golden rings';
assert(gifts.length == 3);
}
//////////////////////////////////////////////////////////
// Functions
void printNumber1(num number) {
print('The number is $number.');
}
printNumber2(number) { // Les types ne sont pas obligatoires.
print('The number is $number.');
}
printNumber3(number) => print('The number is $number.'); // => expr; signifie { return expr;}
// printNumber1 <=> printNumber2 <=> printNumber3
////////////////////////////////////////////////////////
// parameters
String say(String from, String msg, [String device]) { //device est optionnel
var result = '$from says $msg';
return (device != null) ? '$result with a $device' : result;
}
String say2({String from : 'me', String msg : 'none', String device}) { // paramètre nommé optionnel
return say(from, msg, device);
}
saySomething() {
print(say2(from : "Laurent", msg : " Coucou", device : "PC sur Linux Mint."));
}
////////////////////////////////////////////////////////////
// functions are objects
Function printElement = (element) {
print(element);
};
printAll() {
var list = [1,2,3];
list.forEach(printElement); // la fonction est passée en paramètre.
list.forEach(print); // ou encore
list.forEach((element) => print(element)); // ou encore
}
////////////////////////////////////////////////////////
//scope
var topLevel = true;
mainScope() {
var insideMain = true;
myFunction() {
var insideFunction = true;
nestedFunction() {
var insideNestedFunction = true;
assert(topLevel);
assert(insideMain);
assert(insideFunction);
assert(insideNestedFunction);
}
}
}
////////////////////////////////////////////////////////
//closure
/// Returns a function that adds [addBy] to a number.
Function makeAdder(num addBy) {
adder(num i) {
return addBy + i;
}
return adder;
}
mainClosure() {
Function 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);
}
// Other closure example
/* var a = "before";
var modify = () => a = "after";
var read = () { print(a); };
testClosure2() {
modify();
read(); // prints after
}
*/
var a = "Before";
modify(suffix) => (v) => "$v-$suffix";
testClosure2() {
var modAfter = modify("After");
a = modAfter(a);
print(a);
}
////////////////////////////////////////////////////////
// Operator overloading
class MyClass {
operator ==(MyClass other) {
// compare this to other
}
}
///////////////////////////////////////////////////////
// Type operators
class Person {}
void typeOperators() {
Person person;
if (person is Person) { // équivalant à instanceof
person.firstName = 'Bob';
}
(person as Person).firstName = 'Bob'; // cast
}
//////////////////////////////////////////////////////
// Exceptions
buySomeFood() => throw new UnimplementedError();
feedLlamas() => "Llamas are full";
class OutOfFoodException implements Exception {}
takeCareOfLlamas() {
try {
feedLlamas();
} on OutOfFoodException { // Une exception spécifique
buySomeFood();
feedLlamas();
} on Exception catch(e) { // Tout autre exception
print('Unknown exception: $e');
} catch(e) { // N'importe quoi d'autres
print('Something really unknown: $e');
} finally {
print('Clean the dishes');
}
}
///////////////////////////////////////////////////
// Class
class Point {
num x; // Variable d'instance x inititalisée à null.
num y = 0; // Variable d'instance z initialisée à 0.
// les getters et setters sont implicites
// Constructeur
Point(this.x, this.y); // sucre syntaxique
Point.fromJson(Map json) { // constructeur nommé
x = json['x'];
y = json['y'];
}
}
initPoint() {
var p12 = new Point.fromJson(JSON.decode('{"x":1, "y":2}'));
assert(p12.x ==1);
}
//////////////////////////////////////////////////
// Constructeur constant
class ImmutablePoint {
final num x;
final num y;
// vérifie que toutes les variables d'instances soient finales
const ImmutablePoint(this.x, this.y);
static final ImmutablePoint origin = const ImmutablePoint(0, 0);
}
//////////////////////////////////////////////////
// getter and setter
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;
}
initRectangle() {
var rect = new Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
}
///////////////////////////////////////////////
// abstract class
abstract class Doer {
void doSomething(); // méthode abstraite
}
class EffectiveDoer extends Doer {
void doSomething() {
// ...fournit une implémentation de la méthode
}
}
//////////////////////////////////////////////
// override operator
class Vector {
final int x;
final int y;
const Vector(this.x, this.y);
Vector operator +(Vector v) { // Redéfinition de +
return new Vector(x + v.x, y + v.y);
}
Vector operator -(Vector v) { // Redéfinition -
return new Vector(x - v.x, y - v.y);
}
}
testVector() {
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)
}
/////////////////////////////////////////////
// Implicit interface
class User {
final _name; // Dans l'interface, mais visible seulement de la librairie,
User(this._name); // Pas dans l'interface, c'est un constructeur
String hello(who) => 'Hello, $who. I am $_name.'; // Dans l'interface.
}
class Imposter implements User {
final _name = ""; // Obligé de la déclarer, même non utilisé
String hello(who) => 'Hi $who. Do you know who I am?'; // nouvelle implémentation
}
sayHelloToBob(User user) => user.hello('bob');
testImplicit() {
print(sayHelloToBob(new User('kathy')));
print(sayHelloToBob(new Imposter()));
}
/////////////////////////////////////////////
// Extending class
class Television {
void turnOn() {
_illuminateDisplay();
_activateIrSensor();
}
_illuminateDisplay(){ }
_activateIrSensor() { }
void noSuchMethod(Invocation mirror) {
print('Not implemented in $this');
}
}
class SmartTelevision extends Television {
void turnOn() {
super.turnOn();
_bootNetworkInterface();
_initializeMemory();
_upgradeApps();
}
_bootNetworkInterface() { }
_initializeMemory() { }
_upgradeApps() { }
}
testTelevision() {
var smart = new SmartTelevision();
smart._activateIrSensor();
var normal = new Television();
normal._bootNetworkInterface();
}
//////////////////////////////////////////////
// Mixins
class Performer {
String name;
Performer(this.name);
}
// Mixins permet l'héritage multiple sans les contraintes
class Musician extends Performer with Musical {
Musician(name) : super(name);
}
class Maestro extends Musician with Aggressive, Demented {
Maestro(maestroName) : super(maestroName);
}
// Un mixin est une classe :
// sans constructeur
// sans appelle de super
// étend Object
class Musical {
void entertain() {
print('Douce mélodie');
}
}
class Aggressive {}
class Demented {}
//////////////////////////////////////////////
// Generics
void generics() {
var names = new List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
names.add(42); // échoue en checkmode
//ou encore
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' };
}
abstract class Cache<T> {
T getByKey(String key);
setByKey(String key, T value);
}
//////////////////////////////////////////////
// Future
void printDailyNewsDigest() {
File file = new File("dailyNewsDigest.txt");
print(file.readAsStringSync());
}
void printDailyNewsDigestWithFuture() {
File file = new File("dailyNewsDigest.txt");
Future future = file.readAsString();
future.then((content) => print(content))
.catchError((e) => print(e));
}
void chainFuture() {
expensiveA().then((aValue) => expensiveB())
.then((bValue) => expensiveC())
.then((cValue) => doSomethingWith(cValue));
}
expensiveA() => null;
expensiveB() => null;
expensiveC() => null;
doSomethingWith(Object val) => null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment