Hello World
Though the origins of Hello World remain somewhat unclear, its use as a test phrase is widely believed to have begun with Brian Kernigham’s 1972 book, A Tutorial Introduction to the Language B. In this text, the first known version of the program was used to illustrate external variables. Because the previous example in the tutorial printed “hi!” on the terminal, the more complex “hello, world!” required more character constants for expression and was the next step in the learning process.
void main(){
print('Hello, World!');
}
Variables
- String
- int
- float
- list
- Object (json ?)
Control Flow Statements
if …else if ...
for ( ; ; )
for (var x in aList)
while (){}
Functions
int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
var result = fibonacci(20);
- => arrow function
Comments
//
///
/*
*/
Imports
- import core libraries —
import ‘dart:math’;
- import librariy from external package: —
import 'package:test/test.dart';
- import files: —
import ‘path/to/file’;
Classes
Here’s an example of a class with three properties, two constructors, and a method. One of the properties can’t be set directly, so it’s defined using a getter method (instead of a variable).
class Spacecraft {
String name;
DateTime launchDate;
// Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null);
int get launchYear =>
launchDate?.year; // read-only non-final property
// Method.
void describe() {
print('Spacecraft: $name');
if (launchDate != null) {
int years =
DateTime.now().difference(launchDate).inDays ~/
365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
Inheritance
![Dart: What are mixins?. It’s a kind of magic ✨ | by Romain Rastel …](https://azatai.s3.amazonaws.com/2020-08-11-162451.png) |
class Orbiter extends Spacecraft {
double altitude;
Orbiter(String name, DateTime launchDate, this.altitude)
: super(name, launchDate);
}
Mixins
![Dart: What are mixins?. It’s a kind of magic ✨ | by Romain Rastel …](https://azatai.s3.amazonaws.com/2020-08-11-162553.png) |
Mixins keep Dart code reusable across separate classes. It’s the most efficient way to reuse common code from multiple classes that share common behaviors.
A mixin class contains methods to be used by other classes without being their parent. This is how mixins differ from interfaces and abstract classes.
class Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
}
class PilotedCraft extends Spacecraft with Piloted {
// ···
}
he Sketching
mixin defines the common sketch()
method. It takes a message and prints it on console to keep things simple for demonstration.
mixin Sketching {
sketch(String message) {
print(message);
}
}
The Reading
mixin defines dailyReading(String topic)
method. A reading topic is passed as parameter.
mixin Reading {
dailyReading(String topic) {
print("Daily reading on ${topic}");
}
}
The Exercise
mixin defines methods for running and weight training. The running(int mile)
method passes mile
parameter to print the message. The weightTraining(int weights)
method prints the value for weights
parameter.
mixin Exercise {
running(int mile) {
print("Daily run of ${mile} mile(s)");
}
weightTraining(int weights) {
print("Lifting ${weights} lbs");
}
}
The Boxing
mixin defines practicing punches behavior of an athlete. As per our requirements, only athletes are allowed to practice punches. In such cases, we may want to restrict the usage of mixin only by classes of type Athlete. We can apply such restriction on Boxing
mixin by using on
keyword followed by the Athlete
- the class which is allowed the usage.
mixin Boxing on Athlete {
punch(int n) {
print("Boxer practicing ${n} punches");
}
}
The artist makes landscapes sketches. It defines sketchLandscape()
to do so. This method calls sketch(...)
method from Sketching
mixin.
class Artist extends Person with Sketching {
sketchLandscape() {
sketch("Making landscapes sketches");
}
}
The engineer does make building sketches and reads research on building construction. The sketchBuildings()
method uses sketch()
method from Sketching
mixin. The readResearchPaper()
calls dailyReading(topic)
from Reading
mixin.
class Engineer extends Person with Sketching, Reading {
sketchBuildings() {
sketch("Sketching engineering drawings");
}
readResearchPaper() {
String topic = "Building Construction";
dailyReading(topic);
}
}
The athlete *is a* person as well like other people we discussed so far. All athletes do their exercise, and have a general workout routine. The method generalRoutine()
provide the general workout routine definition.
class Athlete extends Person with Exercise {
generalRoutine() {
running(2);
weightTraining(20);
}
}
The boxer *is a* Athlete who does boxing. The Boxing
mixin provides the punch()
to define punchPractice()
method for boxer. The routineExercise()
method defines exercise routine for this specific athlete with help of Exercise
mixin.
class Boxer extends Athlete with Boxing {
punchPractice() {
punch(100);
}
routineExercise() {
running(4);
weightTraining(40);
}
}
I find that using that much mixin actually because of the strong OOP, use classes rather than functins, so we are strongly needed to name a class to use it’s function even we can just simply defind a function. (This is wrong when we can restrict only special kind of classes can use the function.)
Interfaces and Abstract Classes
Dart has no interface
keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.
You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).
Async
for (var object in objects) {
try {
var file = File('$object.txt');
if (await file.exists()) {
var modified = await file.lastModified();
print(
'File for $object already exists. It was modified on $modified.');
continue;
}
await file.create();
await file.writeAsString('Start describing $object in this file.');
} on IOException catch (e) {
print('Cannot create description for $object: $e');
}
}
Exceptions
if (astronauts == 0) {
throw StateError('No astronauts.');
}
try {
for (var object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} on IOException catch (e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}