Skip to content

Instantly share code, notes, and snippets.

@ojhariddhish
Last active May 27, 2017 11:09
Show Gist options
  • Save ojhariddhish/ebf7b9f82a21b5cc1f7d172ae976637a to your computer and use it in GitHub Desktop.
Save ojhariddhish/ebf7b9f82a21b5cc1f7d172ae976637a to your computer and use it in GitHub Desktop.
Learning Dart through Google's Code Labs
class Bicycle {
int cadence;
int _speed; // private & read-only variable using underscore
int gear;
Bicycle(this.cadence, this._speed, this.gear);
int get speed => _speed;
void applyBrake(int decrement) {
_speed -= decrement;
}
void speedUp(int increment) {
_speed += increment;
}
@override
String toString() => 'Bicycle: $_speed mph, gear: $gear';
}
void main() {
var bike = new Bicycle(2, 0, 1);
print(bike);
}
String scream(int length) {
return "A${'a' * length}h!";
}
main() {
var values = [1, 2, 3, 5, 10, 50];
//values.map(scream).forEach(print);
values.skip(1).take(3).map(scream).forEach(print); // 2, 3, 5
/*for (var length in values) {
print(scream(length));
}*/
}
import 'dart:math';
class Rectangle {
int width;
int height;
Point origin;
Rectangle({this.origin = const Point(0,0), this.width = 0, this.height = 0}); // named & default parameters
@override
String toString() => 'Origin: (${origin.x}, ${origin.y}), Width: $width, Height: $height';
}
main() {
print(new Rectangle(origin: const Point(10, 20), height: 200, width: 100)); // position can be changed
print(new Rectangle(origin: const Point(10, 10)));
print(new Rectangle(width: 100));
print(new Rectangle());
}
import 'dart:math';
abstract class Shape {
num get area;
factory Shape(String type) {
if (type == 'circle') return new Circle(2);
if (type == 'square') return new Square(3);
throw 'Can\'t create $type.';
}
}
class Circle implements Shape {
final num radius;
Circle(this.radius);
num get area => PI * pow(radius, 2);
}
class Square implements Shape {
final num side;
Square(this.side);
num get area => pow(side, 2);
}
class CircleMock implements Circle {
num area;
num radius;
}
/*
* Shape shapeFactory(String type) {
if (type == 'circle') return new Circle(2);
if (type == 'square') return new Square(3);
throw 'Can\'t create $type.';
}
*/
main() {
var circle = new Shape('circle');
var square = new Shape('square');
print(circle.area);
print(square.area);
try {
var rhombus = new Shape('rhombus'); // Uncaught exception
}
catch (err) {
print(err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment