DART クイックリファレンス
型、関数、クラス、非同期、null 安全、コレクション
基本
Hello World
void main() {
print('Hello, Dart!');
}
変数
var name = 'Dart'; // 型推論
String lang = 'Dart'; // 明示的な型
final pi = 3.14; // ランタイム定数
const max = 100; // コンパイル時定数
文字列補間
var name = 'World';
print('Hello, $name!');
print('1 + 1 = ${1 + 1}');
型
組み込み型
| int | 64 ビット整数 |
| double | 64 ビット浮動小数点 |
| num | int と double のスーパータイプ |
| String | UTF-16 文字列 |
| bool | true または false |
| List | 順序付きコレクション(配列) |
| Set | 順序なしの一意なコレクション |
| Map | キーと値のペア |
| dynamic | 任意の型、静的チェックを無効化 |
| void | 戻り値なし |
型チェックとキャスト
if (obj is String) print(obj.length);
var s = obj as String; // キャスト
print(obj.runtimeType); // ランタイム型
関数
関数の構文
int add(int a, int b) => a + b;
void greet({required String name}) {
print('Hello, $name');
}
パラメーター
| int f(int a) | 必須の位置パラメーター |
| int f([int a = 0]) | デフォルト値付きのオプション位置パラメーター |
| f({required int a}) | 必須の名前付きパラメーター |
| f({int a = 0}) | デフォルト値付きのオプション名前付きパラメーター |
クロージャとティアオフ
var square = (int n) => n * n;
[1, 2, 3].map((e) => e * 2);
[1, 2, 3].forEach(print); // ティアオフ
制御フロー
条件分岐
if (x > 0) { print('pos'); }
else if (x == 0) { print('zero'); }
else { print('neg'); }
var result = x > 0 ? 'pos' : 'neg';
ループ
for (var i = 0; i < 5; i++) { }
for (var item in list) { }
while (x > 0) { x--; }
do { x--; } while (x > 0);
switch とパターンマッチング
switch (color) {
case 'red': print('R'); break;
case 'blue': print('B'); break;
default: print('?');
}
クラス
クラスの定義
class Point {
final double x, y;
Point(this.x, this.y);
double distanceTo(Point p) =>
sqrt(pow(x - p.x, 2) + pow(y - p.y, 2));
}
名前付きコンストラクタとファクトリコンストラクタ
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
factory Point.fromJson(Map j) =>
Point(j['x'], j['y']);
}
継承
class Animal { void speak() {} }
class Dog extends Animal {
@override
void speak() => print('Woof');
}
ミックスインと拡張
ミックスイン
mixin Flyable {
void fly() => print('Flying');
}
class Bird with Flyable {}
拡張メソッド
extension StringX on String {
String capitalize() =>
'${this[0].toUpperCase()}${substring(1)}';
}
print('hello'.capitalize()); // Hello
抽象クラスと implements
abstract class Shape {
double area();
}
class Circle implements Shape {
final double r;
Circle(this.r);
@override double area() => pi * r * r;
}
非同期/await
Future
Future fetchData() async {
var res = await http.get(uri);
return res.body;
}
Stream
Stream count(int n) async* {
for (var i = 0; i < n; i++) {
yield i;
}
}
エラーハンドリング
try {
var data = await fetchData();
} on HttpException catch (e) {
print('HTTP error: $e');
} catch (e) {
print('Error: $e');
}
コレクション
List 操作
var nums = [1, 2, 3];
nums.add(4);
nums.where((n) => n > 2); // [3, 4]
nums.map((n) => n * 2); // [2,4,6,8]
var sorted = nums..sort();
Map 操作
var m = {'a': 1, 'b': 2};
m['c'] = 3;
m.containsKey('a'); // true
m.entries.map((e) => '${e.key}=${e.value}');
スプレッドとコレクション if/for
var all = [0, ...nums];
var nav = ['Home', if (isAdmin) 'Admin'];
var sq = [for (var i in nums) i * i];
null 安全
null 許容型
| int? | null 許容 int(null になり得る) |
| int | null 非許容 int(null にならない) |
| ! | null アサーション演算子 |
| ?. | null 安全アクセス |
| ?? | null の場合のデフォルト値 |
| ??= | null の場合に代入 |
| late | 遅延初期化 |
null 安全の例
String? name; // null 許容
int len = name?.length ?? 0;
late final String title; // 使用前に設定
name ??= 'default'; // null の場合に代入
よくあるパターン
値付き enum
enum Color {
red('FF0000'), green('00FF00');
final String hex;
const Color(this.hex);
}
レコードと分割代入
(String, int) userInfo() => ('Alice', 30);
var (name, age) = userInfo();
print('$name is $age');
シールドクラス
sealed class Shape {}
class Circle extends Shape { final double r; Circle(this.r); }
class Rect extends Shape { final double w, h; Rect(this.w, this.h); }