1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】Extension 整理

1
Posted at

1. 定義

Extension(拡張メソッド) は、
既存のクラスに 新しいメソッドを追加できるように見せる 言語機能です。

  • クラス自体を編集せずに機能を増やせる
  • 実態は シンタックスシュガー(糖衣構文)
  • コンパイル時に解決される(実行時オーバーヘッドなし)
  • 代表言語:Dart(Flutter)、Kotlin、C# など

2. 特徴

  • クラスを変更できない/したくない場合でも拡張可能
  • インスタンスメソッドのように自然に呼び出せる
  • Decorator のように 実行時ラップ ではなく、静的に解決
  • API の利便性を高めるのに有効

3. Flutter / Dart の例

extension StringExtension on String {
  String reversed() => split('').reversed.join();
}

void main() {
  print("Anna".reversed()); // annA
}
  • extensionStringreversed() を追加
  • 実際には StringExtension.reversed("Anna") に展開される
  • 既存の String クラスを変更していない

4. Kotlin の例

fun String.reversedEx(): String = this.reversed()

fun main() {
    println("Anna".reversedEx()) // annA
}
  • Kotlin でも同様に String にメソッドを追加できる
  • 実態は静的関数 StringExtensions.reversedEx("Anna")

5. 実務ユースケース

Flutter / Dart

  • DateTime のフォーマット関数を追加
  • ネットワークレスポンスの変換関数を追加
  • BuildContext に便利メソッドを生やす(例:context.showSnackBar()

Kotlin

  • String / Collection に便利メソッド追加 (isEmail(), toSnakeCase())
  • Android Context に拡張関数を生やす (Context.showToast())
  • Retrofit や Coroutine のユーティリティ関数

6. Extension と他の拡張手法の違い

手法 タイミング 作用対象 主な用途 Flutter 例
Extension コンパイル時 API に便利メソッド追加 String.reversed()
Mixin コンパイル時 クラス 共通機能を注入 with ChangeNotifier
Decorator 実行時 オブジェクト 責務を後付け Padding(Text())

まとめ

  • Extension = 既存型に新しいメソッドを追加できる仕組み
  • 実態は静的解決の糖衣構文 → パフォーマンスコストなし
  • Decorator / Mixin と同じ「拡張」でも仕組みと用途が違う
  • Flutter / Kotlin 実務で「便利関数の整理」に必須
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?