Dart 中的事件和事件句柄

Event and EventHandle in Dart

我来自 C#,我了解(或多或少)围绕事件的逻辑及其工作方式。现在,我必须将事件范例(通过数据传递)从 C# 传到 Dart,但我不明白它在 Dart 上是如何工作的。谁能耐心给我解释一下?谢谢

编辑:这些是我必须翻译的代码片段

Class Engine.cs

public class Engine {
    [...]
    public event EventHandler<EngineComputationEventArgs> ComputationCompleted;

     protected virtual void OnComputationCompleted(Result result) {
         var evt = ComputationCompleted;
         if (evt != null) {
             evt(this, new EngineComputationEventArgs(result));
         }
     }
}

Class Example.cs

[...]

engine.ComputationCompleted += (sender, e) => {
    Console.WriteLine("PPE {0}", e.Result.Ppe);
};

[...]

EngineComputationEventArgs.cs

public class EngineComputationEventArgs : EventArgs {

    public EngineComputationEventArgs(Result result) {
        Result = result;
    }

    public Result Result { get; private set; }

}

Dart 没有像 C# 那样的内置“事件”类型。您通常使用 Stream 作为事件发射器,并使用相应的 StreamController 向其添加事件。

示例:

class Engine {
  final StreamController<EngineComputationEventArgs> _computationCompleted =
     StreamController.broadcast(/*sync: true*/);

  Stream<EngineComputationEventArgs> get computationCompleted => 
      _computationCompleted.stream;

  void onComputationCompleted(Result result) {
    if (_computationCompleted.hasListener) {
      _computationCompleted.add(EngineComputationEventArgs(result));
    }
  }
}

然后您通过监听流来添加监听器:

engine.computationCompleted.forEach((e) =>
    print("PPE ${e.result.ppe}"));

var subscription = engine.computationCompleted.listen((e) =>
    print("PPE ${e.result.ppe}"));
// Can call `subscription.cancel()` later to stop listening.

你的“args”class可能是(因为我对EventArgs一无所知)

class EngineComputationEventArgs extends EventArgs {
  final Result result;
 
  EngineComputationEventArgs(this.result);
}