Dart 3.10では、コードをより簡潔に記述できるdot shorthandsが導入されました。 この機能を使うことで、特定のプロパティやメソッドにアクセスするコードを短縮して記述できます。 今までと書き方や見た目が結構変わるので、最初は戸惑うかもしれませんが、慣れてくるとこちらのほうが見やすいと感じるようになると思います。
10/4時点では、Flutter 3.10がリリースされていないため、Flutterでの利用はできませんが、3.36.0のbeta以降では利用可能です。
new
例えば、以下のようなコードがあるとします
class Person {
final String name;
final int age;
Person(this.name, this.age);
}
Before
final alice = Person('Alice', 25);
print(alice.age); // 25
After
Dart 3.10以降では、newを使って以下のように記述できます
Person bob = .new('Bob', 30);
print(bob.age); // 30
factory
factoryコンストラクタやにもdot shorthandsを使用できます。
class Person {
final String name;
final int age;
Person(this.name, this.age);
factory Person.born(String name) {
return Person(name, 0);
}
}
Before
final charlie = Person.born('Charlie');
print(charlie.age); // 0
After
Person charlie = .born('Charlie');
print(charlie.age); // 0
static
factory同様にstaticメンバーにもdot shorthandsを使用できます。
class Person {
final String? name;
final int age;
static Person anonymous = .new(null, 0);
Person(this.name, this.age);
factory Person.born(String name) {
return Person(name, 0);
}
}
Before
final anonymous = Person.anonymous;
print(anonymous.name); // null
After
Person anonymous = .anonymous;
print(anonymous.name); // null
staticメソッドが使えるので、既存のコードをこのように書き換えることも可能になります。
int value = .parse('100');
ちなみにnullableでも使えます。
int? nullableValue = .parse('100');
Enum
一番使えそうなのはenumでしょうか。
enum Color {
red,
green,
blue
}
Before
final favorite = Color.red;
print(favorite); // Color.red
After
Color favorite = .red;
print(favorite); // Color.red
switch文でも使えます。
Color favorite = .red;
switch (favorite) {
case .red:
print("Red");
case .green:
print("Green");
case .blue:
print("Blue");
}
// Red
if文だとこんな感じになります。
if (favorite == .red) {
print("It's red!");
}
if (favorite case == .red) {
print("It's red!");
}
これはかなりスッキリして良い変更だと思います。
Flutterのユースケース
Flutterの場合はこんな感じで使えるようになります。
class ExampleWidget extends StatelessWidget {
const ExampleWidget({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: .center,
crossAxisAlignment: .center,
verticalDirection: .down,
children: [
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: .circular(12),
),
),
SizedBox(height: 16),
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: .new(0xFF2196F3),
borderRadius: .circular(12),
),
),
],
);
}
}
MainAxisAlignmentやColorの設定、BorderRadiusGeometryの設定など、頻繁に使う部分で冗長な表記が減るためかなり見やすくなります。
Colorsの部分は引数の型が Color
になるため、color: .amber
のように書くことはできませんが、newを使うことで短縮できます。
Flutterをずっとやっている人からすると最初は慣れないかもしれませんが、慣れてくるとこちらのほうが見やすいと感じるようになると思います。
まとめ
Dart 3.10で導入されたdot shorthandsを紹介しました。
Flutterには次のバージョンで導入されると思われますが、現在はBeta版でのみ利用可能です。
宣言的UIの記法として、順当な進化をしていると思うので、dart shorthandsの書き方に慣れていきましょう!