Flutter 簡單代理(delegate)實作

Flutter Sep 30, 2020

首先,介绍一下 Dart Mixin,理解 mixin 概念的關鍵在於理解中間類。

維基百科中這樣定義 mixin:

In object-oriented programming languages, a Mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes.

即,mixin 是另外一個普通類,我們可以在不繼承的情況下從此類”借用”方法和變數。

Support for the mixin keyword was introduced in Dart 2.1. Code in earlier releases usually used abstract class instead.

從這個角度來講,mixin 像是 abstract class。

Java tries to make up for this by using Interfaces, but that is not as useful or flexible as mixins.

從這個角度可以認為 mixin 是帶實現的接口。

  • mixin 有點類似 abstract class
  • mixin 有點類似 interface
  • 不能繼承 mixin
  • 可以使用 mixin, abstract class, class 來作為 mixin

演示一個鬧鐘:

lib/alarm.dart

import 'dart:async';

mixin AlarmDelegate {
  void onUpdateTimes(int newSeconds);
  void onTimesUp();
}

class Alarm {
  
  AlarmDelegate delegate;

  Timer _timer;
  int _seconds;

  Alarm() {
    this._seconds = 0;
  }

  void startTimer(int seconds) {
    // this._seconds = seconds;
    print("startTimer, _seconds=${this._seconds = seconds}");
    disposeTimer();
    const oneSec = const Duration(seconds: 1);
    if(this._seconds != 0) {
      this._timer = new Timer.periodic(
        oneSec,
        (Timer timer) => timerEvent(),
      );
    }
  }

  void timerEvent() {
    if (this._seconds < 1) {
      disposeTimer();
      delegate.onTimesUp();
    } else {
      this._seconds = this._seconds - 1;
      print("timerEvent, _seconds=$_seconds");
      delegate.onUpdateTimes(_seconds);
    }
  }

  void disposeTimer() {
    if (null != this._timer) {
      this._timer.cancel();
      this._timer = null;
    }
  }
  
}

lib/main.dart (本例修改自Flutter新專案示例)

在您的State <>類中,實現AlarmDelegate方法。 如下(詳閱Github)。

class _MyHomePageState extends State<MyHomePage> with AlarmDelegate {
    Alarm mAlarm;

    @override
    void initState() {
        // TODO: implement initState
        super.initState();

        this.mAlarm = Alarm();
        this.mAlarm.delegate = this;
    }
  }

//When event comes, abstract method will call.
  @override
  void onUpdateTimes(int newSeconds) {
    // TODO: implement onUpdateTimes
  }

  @override
  void onTimesUp() {
    // TODO: implement onTimesUp
  }
  

DEMO

這邊是Github

der1598c/Flutter_Exploration
This is my first Flutter exploration repo(contained basic skill for flutter code). - der1598c/Flutter_Exploration

Tags