2019-12-06 实习期学习记录
1. Hello world
main() {
print('Hello, World!');
}
2. Function
// A function declaration.
int timesTwo(int x) {
return x * 2;
}
// Arrow syntax is shorthand for `{ return expr; }`.
int timesFour(int x) => timesTwo(timesTwo(x));
// Functions are objects.
int runTwice(int x, Function f) {
for (var i = 0; i < 2; i++) {
x = f(x);
}
return x;
}
main() {
print("4 times two is ${timesTwo(4)}");
print("4 times four is ${timesFour(4)}");
print("2 x 2 x 2 is ${runTwice(2, timesTwo)}");
}
I/flutter ( 8682): 4 times two is 8
I/flutter ( 8682): 4 times four is 16
I/flutter ( 8682): 2 x 2 x 2 is 8
3. Control flow
bool isEven(int x) {
// An if-else statement.
if (x % 2 == 0) {
return true;
} else {
return false;
}
}
List<int> getEvenNumbers(Iterable<int> numbers) {
var evenNumbers = <int>[];
// A for-in loop.
for (var i in numbers) {
// A single-line if statement.
if (isEven(i)) evenNumbers.add(i);
}
return evenNumbers;
}
main() {
var numbers = List.generate(10, (i) => i);
print(numbers);
print(getEvenNumbers(numbers));
}
I/flutter ( 8682): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I/flutter ( 8682): [0, 2, 4, 6, 8]
4. Strings
main() {
print('a single quoted string');
print("a double quoted string");
// Strings can be combined with the + operator.
print("cat" + "dog");
// Triple quotes define a multi-line string.
print('''triple quoted strings
are for multiple lines''');
// Dart supports string interpolation.
var pi = 3.14;
print('pi is $pi');
print('tau is ${2 * pi}');
}
I/flutter ( 8682): a single quoted string
I/flutter ( 8682): a double quoted string
I/flutter ( 8682): catdog
I/flutter ( 8682): triple quoted strings
I/flutter ( 8682): are for multiple lines
I/flutter ( 8682): pi is 3.14
I/flutter ( 8682): tau is 6.28
5. Collection literals
// A list literal.
var lostNumbers = [4, 8, 15, 16, 23, 42];
// A map literal.
var nobleGases = {
'He': 'Helium',
'Ne': 'Neon',
'Ar': 'Argon',
};
// A set literal.
var frogs = {
'Tree',
'Poison dart',
'Glass',
};
main() {
print(lostNumbers.last);
print(nobleGases['Ne']);
print(frogs.difference({'Poison dart'}));
}
I/flutter ( 8682): 42
I/flutter ( 8682): Neon
I/flutter ( 8682): {Tree, Glass}
6. Classes
// Abstract classes can't be instantiated.
abstract class Item {
use();
}
// Classes can implement other classes.
class Chest<T> implements Item {
List<T> contents;
// Constructors can assign arguments to instance variables using `this`.
Chest(this.contents);
use() => print("$this has ${contents.length} items.");
}
class Sword implements Item {
int damage = 5;
use() => print("$this dealt $damage damage.");
}
// Classes can extend other classes.
class DiamondSword extends Sword {
int damage = 50;
}
main() {
// The 'new' keyword is optional.
var chest = Chest<Item>([
DiamondSword(),
Sword(),
]);
chest.use();
for (var item in chest.contents) {
item.use();
}
}
I/flutter ( 8682): Instance of 'Chest<Item>' has 2 items.
I/flutter ( 8682): Instance of 'DiamondSword' dealt 50 damage.
I/flutter ( 8682): Instance of 'Sword' dealt 5 damage.
7. Computer Pi (暂不深究)
import 'dart:math' show Random;
main() async {
print('Compute π using the Monte Carlo method.');
await for (var estimate in computePi().take(100)) {
print('π ≅ $estimate');
}
}
/// Generates a stream of increasingly accurate estimates of π.
Stream<double> computePi({int batch = 100000}) async* {
var total = 0;
var count = 0;
while (true) {
var points = generateRandom().take(batch);
var inside = points.where((p) => p.isInsideUnitCircle);
total += batch;
count += inside.length;
var ratio = count / total;
// Area of a circle is A = π⋅r², therefore π = A/r².
// So, when given random points with x ∈ <0,1>,
// y ∈ <0,1>, the ratio of those inside a unit circle
// should approach π / 4. Therefore, the value of π
// should be:
yield ratio * 4;
}
}
Iterable<Point> generateRandom([int seed]) sync* {
final random = Random(seed);
while (true) {
yield Point(random.nextDouble(), random.nextDouble());
}
}
class Point {
final double x, y;
const Point(this.x, this.y);
bool get isInsideUnitCircle => x * x + y * y <= 1;
}
I/flutter ( 8682): Compute π using the Monte Carlo method.
I/flutter ( 8682): π ≅ 3.14396
I/flutter ( 8682): π ≅ 3.14426
I/flutter ( 8682): π ≅ 3.1424666666666665
I/flutter ( 8682): π ≅ 3.14335
I/flutter ( 8682): π ≅ 3.140312
参考: