dart
The minimal entry point every Dart program starts from.
void main(List<String> arguments) {
print('Hello world!');
}
The minimal entry point every Dart program starts from.
void main(List<String> arguments) {
print('Hello world!');
}
var / final / const, and how Dart infers types at compile time.
void main() {
int num1 = 2;
double num2 = 3.0;
bool isTrue = true;
print((num1 + num2) is int);
print((num1 + num2).runtimeType);
String str = 'hello';
print('The type of $str is a String? ${str is String}');
var username = 'fireship';
username = 'fireship_dev';
final String fullname = 'Jeffrey';
const int age = 75;
}
Math, logic, cascades (..), null-coalescing (??=), and casts.
void main() {
// Basic Math
1 + 2 - 3 * 4 / 5;
// Logic
1 == 1;
1 < 2;
(1 >= 1) || ('a' == 'b');
var x = 1;
x++; // x = x + 1
x--; // x = x - 1
// Assignment
String? name;
name ??= 'Guest';
// Ternary
String color = 'blue';
var isThisBlue = color == 'blue' ? 'Yep, blue it is' : 'Nah, it aint blue';
// Cascade
var paint = Paint()
..color = 'black'
..strokeCap = 'round'
..strokeWidth = 5.0;
// Typecast
var number = 23 as String;
number is String; // true
}
if/else, for, while, do-while, and assert.
void main() {
// CONDITIONALS
String color = 'blue';
if (color == 'blue') {
//
} else if (color == 'green') {
//
} else {
// default
}
if (color == 'red') print('hello red!');
// LOOPS
for (var i = 0; i < 5; i++) {
print(i);
// break;
// continue;
}
int i = 0;
while (i < 5) {
print(i);
i++;
}
i = 0;
do {
print(i);
} while (i < 5);
// Assert
var txt = 'good';
assert(txt != 'bad');
}
Named params, arrow syntax, and functions as first-class values.
void main() {
// Basic Function
String takeFive(int number) {
return '$number minus five equals ${number - 5}';
}
takeFive(23);
// Named parameters
namedParams({required int a, int b = 5}) {
return a - b;
}
namedParams(a: 23, b: 10);
// Arrow Function
takeTen(int number) => '$number minus ten equals ${number - 10}';
takeTen(23);
// First-class functions
callIt(Function callback) {
var result = callback();
return 'Result: $result';
}
var cool = callIt;
// Anonymous Function
callIt(() => 'hola mundo!');
}
Core List methods, iteration, spread (...) and collection-if.
void main() {
List<int> list = [1, 2, 3, 4, 5];
list[0];
list.sublist(2, 5);
var list2 = List.filled(50, 'hello');
list.length;
list.last;
list.first;
list.add(4); //push
list.removeLast(); //pop
list.insert(1, 1000);
for (int n in list) {
print(n);
}
for (var n in list) {
print(n);
}
var doubled = list.map((n) => n * 2);
doubled.forEach(print);
var combined = [...list, ...doubled];
combined.forEach(print);
bool depressed = false;
var cart = ['milk', 'eggs', if (depressed) 'Oats'];
}
Map access, entries, and iteration patterns.
void main() {
Map<String, dynamic> book = {
'title': 'Moby Dick',
'author': 'Herman Melville',
'pages': 752,
};
book['title'];
book['published'] = 1851;
book.keys;
book.values;
book.values.toList();
for (MapEntry b in book.entries) {
print('Key ${b.key}, Value ${b.value}');
}
book.forEach((k, v) => print("Key : $k, Value : $v"));
}
Fields, constructors, and static members.
void main() {
Basic thing = new Basic(55);
thing.id;
thing.doStuff();
Basic.helper();
}
class Basic {
int id;
Basic(this.id);
doStuff() {
print('Hello my ID is $id');
}
static helper() {}
}
Positional/optional params, const constructors, and named constructors.
void main() {
var rect = Rectangle(25, 30);
const cir = Circle(radius: 50, name: 'foo');
var p1 = Point.fromMap({'lat': 23, 'lng': 50});
var p2 = Point.fromList([23, 50]);
}
class Rectangle {
final int width;
final int height;
String? name;
late final int area;
Rectangle(this.width, this.height, [this.name]) {
area = width * height;
}
}
class Circle {
const Circle({required int radius, String? name});
}
class Point {
double lat = 0;
double lng = 0;
// Named constructor
Point.fromMap(Map data) {
lat = data['lat'];
lng = data['lng'];
}
Point.fromList(List data) {
lat = data[0];
lng = data[1];
}
}
Nullable types (?), the assertion operator (!), and late fields.
void main() {
// int age = null // error;
int? age;
print(age == null); // true
// eliminates need for null checks
if (age != null) {
// do something
}
// Assertion operator ! Make the compiler think the value is non-null
String? answer;
// String result = answer; // error;
String result = answer!;
}
// late initialization
class Animal {
late final String _size;
void goBig() {
_size = 'big';
print(_size);
}
}
Every class is an implicit interface; leading _ marks library-private.
void main() {
var e = Elephant('Bob');
// works everywhere
e.sayHi();
// only works in this file
e._saySecret();
}
class Elephant {
// Public interface
final String name;
// In the interface, but visible only in this library. (private)
final int _id = 23;
// Not in the interface, since this is a constructor.
Elephant(this.name);
// Public method.
sayHi() => 'My name is $name.';
// Private method.
_saySecret() => 'My ID is $_id.';
}
Single inheritance with extends, super, and @override.
void main() {}
abstract class Dog {
void walk() {
print('walking...');
}
}
class Pug extends Dog {
String breed = 'pug';
@override
void walk() {
super.walk();
print('I am tired. Stopping now.');
}
}
Reusing behavior across classes with the with keyword.
void main() {
var s = SuperHuman();
s.benchPress();
s.sprint();
}
class Human {}
class SuperHuman extends Human with Strong, Fast {}
mixin Strong {
bool doesLift = true;
void benchPress() {
print('doing bench press...');
}
}
mixin Fast {
bool doesRun = true;
void sprint() {
print('running fast...');
}
}
Type-parameterized classes like Box<T>.
void main() {
Box<String> box1 = Box('cool');
Box<double> box2 = Box(2.23);
Box<List<int>> box3 = Box([1, 2, 3]);
}
class Box<T> {
T value;
Box(this.value);
T openBox() {
return value;
}
}
Async work with Future, .then/.catchError, and async/await.
import 'dart:async';
void main() {
var delay = Future.delayed(Duration(seconds: 5));
delay
.then((value) => print('I have been waiting'))
.catchError((err) => print(err));
runInTheFuture();
}
Future<String> runInTheFuture() async {
var data = await Future.value('world');
return 'hello $data';
}
Sequences of async events with listen() and await for.
import 'dart:async';
void main() {
var stream = Stream.fromIterable([1, 2, 3]);
stream.listen((event) => print(event));
stream.map((event) => event * 2).listen((event) => print(event));
streamFun();
}
streamFun() async {
var stream = Stream.fromIterable([4, 5, 6]);
await for (int value in stream) {
print(value);
}
}
Import aliasing (as), and filtering with show/hide.
import 'constructors.dart' as External;
import 'constructors.dart' hide Circle;
import 'constructors.dart' show Rectangle;
class Circle {}
void main() {
Circle();
External.Circle(radius: 10);
Rectangle(1, 2);
}