Dart (programming language): Difference between revisions

Content deleted Content added
History: date for Dart 2.6
Line 225:
<syntaxhighlight lang="dart">
void main() {
print('Hello, World!');
}
</syntaxhighlight>
Line 233:
<syntaxhighlight lang="dart">
void main() {
for (varint i = 1; i <= 10; i++) {
print(i);
}
}
</syntaxhighlight>
Line 243:
<syntaxhighlight lang="dart">
void main() {
var int i = 20;
print('fibonacci($i) = ${fibonacci(i)}');
}
 
Line 264:
class Point {
 
// Final variables cannot be changed once they are assigned.
// Declare two instance variables.
final num x, y;
 
// A constructor, with syntactic sugar for setting instance variables.
// The constructor has two mandatory parameters.
Point(this.x, this.y);
 
// A named constructor with an initializer list.
Point.origin():
: x = 0, y = 0;
y = 0;
 
// A method.
num distanceTo(Point other) {
var num dx = x - other.x;
var num dy = y - other.y;
return math.sqrt(dx * dx + dy * dy);
}
// Example of a "getter".
// Acts the same as a final variable, but is computed on each access.
num get magnitude => math.sqrt(x * x + y * y);
 
// Example of operator overloading
Point operator +(Point other) => Point(x + other.x, y + other.y);
// When instantiating a class such as Point in Dart 2+, new is
// an optional word
}
 
// All Dart programs start with main().
void main() {
// Instantiate point objects.
var Point p1 = Point(10, 10);
print(p1.magnitude);
var Point p2 = Point.origin();
var num distance = p1.distanceTo(p2);
print(distance);
}
</syntaxhighlight>