1
2

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】Mixin(ミックスイン)とは?

1
Posted at

1. 定義

Mixin(ミックスイン) は、
クラスに対して 共通の機能を“混ぜ込む”ように再利用する仕組み です。

  • 多重継承の代替手段
  • クラスに横断的な機能(ログ、通知、状態管理など)を追加可能
  • 静的(コンパイル時) に解決される言語機能

2. 特徴

  • 継承を使わずに機能を注入できる
  • 1つのクラスに 複数の Mixin を同時に適用できる
  • Decorator のように「実行時ラップ」ではなく、コンパイル時に型に混ぜ込む
  • Dart, Python, Scala, Ruby などがネイティブにサポート
  • Kotlin / Java では interface + default method で代替可能

3. Flutter / Dart の例

mixin Logger {
  void log(String message) {
    print("[LOG] $message");
  }
}

class Service with Logger {
  void fetchData() {
    log("Fetching data...");
  }
}

void main() {
  var service = Service();
  service.fetchData(); // [LOG] Fetching data...
}
  • Logger → Mixin として定義
  • Servicewith Logger を付与するだけでログ機能を利用可能

4. Kotlin の例(代替)

Kotlin には mixin 構文はないですが、interface にデフォルト実装を持たせることで同じ役割を果たせます。

interface Logger {
    fun log(message: String) {
        println("[LOG] $message")
    }
}

class Service : Logger {
    fun fetchData() {
        log("Fetching data...")
    }
}

fun main() {
    val service = Service()
    service.fetchData() // [LOG] Fetching data...
}

5. 実務ユースケース

Flutter / Dart

  • ChangeNotifierwith で注入(状態管理)
  • SingleTickerProviderStateMixin(アニメーション制御)
  • AutomaticKeepAliveClientMixin(タブ画面で状態保持)

Kotlin

  • interface + default 実装を mixin 的に利用
  • ログ、監査、認証、共通ユーティリティをクラスに横断的に付与

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

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

7. まとめ

  • Mixin = クラスに機能を静的に混ぜ込む仕組み
  • 多重継承の代替として、コード再利用や横断的関心事を注入できる
  • Decorator(動的ラップ)Extension(静的メソッド追加) とは別物
  • Flutter では状態管理や UI 制御で頻繁に使われる
1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?