main関数
void main() {
print('Hello world');
}
変数、データタイプ、コメント
// コメント
/*
コメント
*/
// 宣言と代入
var i = 1; // int
var d = 0.8; // double
int ii = 2; // int定義
double dd = 1.42e5; // double
// 特別な型 dynamic。使う型が決まっている場合の定義
dynaimc value;
value = '文字列'; // dynamic String
value = 0; // dynamic int
value = 1.0; // dynamic double
bool b = true; // bool
// 変更できない
const cn = 20000000; // コンパイル時に決定
final fn = 1000000; // 設定時に決定
// 列挙型
enum Color { red, blue, white }
final color = Color.red;
演算子
10+2; // 12
10-2; // 8
10*2; // 20
10/2; // 5
10.5 ~/ 2.0; // 5。intの5
10 / 3; // 1。割り算の余り
var i = 10.0/2.0; // 5。型は、int
i++; // 6
--i; // 5。i--もある。
// 比較
1<2; // true;
1>2; // false;
1<=2; // true;
1>=2; // true;
i+=1; // 6
i-=1; // 5
i*=2; // 10
i/=2; // 5
Null
int i;
double d;
String s;
// Null演算子
var err = s ?? 'No error'; // 「??」 sがnullの時に代入
s ??= err; // 「??=」sがnullの時に代入
print(i?.isEven); // 「.?」null参照でも例外を出さない。nullを出力。
文字列
var s1='123';
String s2="456";
var s3='$s1 $s2'; // 123 456
var s4='123¥'' + '456¥n' + "78¥""; // 123'456(改行)78"
var s5='123¥'' '456¥n' "78¥""; // 123'456(改行)78"
var s6='''123'456
78"'''; // 123'456(改行)78"
var s7=r"123'456¥n78"; // 123'456¥n78
制御
// if
var s = '1';
if (s == '1') {
print(s);
} else if (s == "2") {
print(s);
} else {
print(s);
}
// switch
enum Color {red, blue, yellow, white} // 別で宣言しておくこと
Color color = Color.white;
switch(color) {
case Color.red:
case Color.blue:
print(color);
break;
case Color.yellow:
print(color);
break;
default:
print(color); // Color.white。ここが呼ばれる
}
// loop
var i = 10;
while(i < 10) {
print(i);
i++;
}
i = 10;
do {
print(i);
i++;
} while( i < 10);
for (i=1; i<10;i++) {
print(i);
}
var l=[1,2,3,4];
for (var n in l) {
if (n == 2) {
continue;
}
print(n);
if (n == 3) {
break;
}
}
l.forEach(print);
l.forEach((v) => print(v));
関数
bool isEmpty(String value) {
return value == null;
}
var s = '1';
isEmpty(s); // false
String fn1(String s1, String s2, [String s3]) {
return '${title == null ? "" : "$title "}$s1$s2';
}
fn1("aaa", "bbb"); // aaabbb
fn1("aaa", "bbb", "ccc"); // ccc aaabbb
bool range(int value, {int min, int max}) {
retur (min ?? int.int64MinValue) <= value && value <= (max ?? int.int64MaxValue);
return true;
}
range(11, max: 10, min: 1); // false;
bool range2(int value, {int min=int.int64MinValue, int max=int.int64MaxValue}) {
return min <= value && value <= max;
}
range2(5); // true;
int applyTo(int value, int Function(int) fn) {
return op(value);
}
int square(int n) {
return n * n;
}
applyTo(3, square); // 9
int multiply(int a, int b) => a * b;
multiply(14, 3); // 42
// 無名関数
var fn1 = (int a, int b) {
return a * b;
}
fn1(14, 3); // 42
// クロージャ
Function fn2(num n) {
return (num value) => value * n; // fn3(value) => value * 3
}
var fn3 = fn2(3);
fn3(14.0); // 42.0
コレクション
var l = List<String>(2);
l[0] = '1';
l[1] = '2';
List<String> l2 = [];
l2.add('1');
var l3 = ['1','2'];
l3.length; // 2
l3.first; // '1'
l3.last; // '2'
l3.isEmpty; // false
l3.isNotEmpty; // true
l3.forEach(print); // [1, 2]
// コレクション if
['1', '2', if (false) '3']; // [1, 2]
['1', '2', if (true) '3']; // [1, 2, 3]
// コレクション for
[for (var n in [1,2,3]) 2 * n]; // [2, 4, 6]
// List演算子
var l7 = ['2','3'];
var ll;
var l8 = ['1', ...l7, ...?ll];
[1, 2, 3, 4].map((number) => number * number).toList(); // [1,4,9,16]
[1,4,9,16].where((number) => number.isEven); // (4,16)。Iterable<int> 。偶数
[1, 2, 3, 4, 5].reduce((value, element) => value + element); // 15
// セット
var s1 = <int>{};
var s2 = {1,2,3,1};
s2.contains(1); // true
s2.contains(-1); // false
s2.add(4);
s2.remove(4);
s2.addAll([1,2,3,4,5,6]);
var s3 = s1.intersection(s2);
var s4 = s1.union(s2);
// マップ
var m1 = Map<String, int>();
var m2 = {'a':'1', 'b':'2'};
var s = m2['a'];
m2.containsKey('a'); // true
m2.containsValue('3'); // false
m2.keys.forEach(print);
m2.values.forEach(print);
m2.forEach((key, value) => print('$key : $value'));
クラスとオブジェクト
class Actor {
String name;
var filmography = <String>[];
Actor(this.name, this.filmography);
Actor.rey({this.name = 'Daisy Ridley'}) {
filmography = ['The Force Awakens', 'Murder on the Orient Express'];
}
Actor.inTraining(String name) : this(name, []);
Actor.gameOfThrones(String name)
: this.name = name,
this.filmography = ['Game of Thrones'] {
print('My name is ${this.name}');
}
String get debut => '$name debuted in ${filmography.first}';
set debut(String value) => filmography.insert(9, value);
void signOnForSequel(String franchiseName) {
filmography.add('Upcomming $franchiseName sequel');
}
String toString() => '${[name, ...filmography].join("¥n- ")}¥n';
}
var gotgStar = Actor('Zoe Saldana', []);
gotgStar.name = 'Zoe Sadana';
gotgStar.filmography.add('Guardians of the Galaxy');
gotgStar.debut = 'Center Stage';
print(Actor.rey().debut); // The Force Awakens
var kit = Actor.gameOfThrones('Kit Harington');
var star = Actor.inTraining('Super Start');
gotgStar // Get on object
..name = 'Zoe' // Use property
..signOnForSequel('Star Trek'); // Call method
静的クラス
enum PhysicistType { theoretical, experimental, both}
class Physicist {
String name;
PhysicistType type;
Physicist._internal(this.name, this.type);
static var physicistCount = 0;
static Physicist newPhysicist(
String name,
PhysicistType type) {
physicistCount++;
return Physicist._internal(name, type);
}
}
}
final emmy = Physicist.newPhysicist('Emmy Noether', PhysicistType.theoretical);
final lise = Physicist.newPhysicist('Lise Meitner', Physicist.experimental);
print(Physicist.physicistCount); // 2
クラス継承
class Person {
String firstName;
String lastName;
Person(this.firstName, this.lastName);
String get fullName => '$firstName $lastName';
@override
String toString() => fullName;
}
class Student extends Person {
var grades = <String>[];
Student(String firstName, String lastName) : superfirstName, lastName);
@override
String get fullName => '$lastName, $frstName';
}
final jon = Person('Jon', 'Snow');
final jane = Student('Jane', 'Snow');
print(jon); // Jon Snow
print(jane); // Snow, Jone
Abstract, 継承, ミックスイン
enum BloodType {warm, cold}
abstract lass Animal {
BloodType bloodType;
void goSwimming();
}
mixin Milk {
bool hasMilk;
bool doIHaveMilk() => hasMilk;
}
class Cat extends Animal with Milk {
BloodType bloodType = BloodType.warm;
Cat() {hasMilk = true;}
@override
void goSwimming() { print('No thanks'); }
}
class Dolphin extens Animal implements Comparable<Dolphin> {
BloodType bloodtype = BloodType.warm;
double length;
Dolphin(this.length);
@override
void goSwimming() { print('Click'); }
@override
int compareTo(other) => length.compareTo(other.length);
@override
String toString() => '$length meters';
}
class Reptile extends Animal with Milk {
BloodType bloodType = BloodType.cold;
Reptile() {hasMilk.false;}
@override
void goSwimming() {pring('Suer');}
}
var garfield = Cat();
var flipper = Dolphin(4.0);
var snake = Reptile();
flipper.goSwimming(); // Click
garfield.goSwimming(); // No thanks
var orca = Dolphin(8.0); var alpha = Dolphin(5.0);
var dolphins = [alpha, orca, flipper];
dolphins.sort();
print(dolphins); // 4 meters, 5meters, 8meters];
print(snake.doIHaveMilk()); // false;
print(garfield.doIHaveMilk()); // true
コメント