【问题标题】:Event and EventHandle in DartDart 中的事件和事件句柄
【发布时间】:2022-01-23 12:50:31
【问题描述】:

我来自 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 中的 FutureStream 的一些描述吗?
  • 我用我必须翻译的代码编辑了帖子,但要简短的是,我想了解 Future 和 Stream 如何在 Dart 中工作(我认为我需要使用其中一个翻译)

标签: dart events event-handling


【解决方案1】:

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”类可能是(因为我对EventArgs一无所知)

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

【讨论】:

  • 解决方案有效...您能否解释一下StreamFuture 之间的区别以及为什么我应该使用其中一个而不是另一个
  • 我推荐阅读语言教程中的FuturesStreams
猜你喜欢
  • 2023-03-28
  • 2010-12-17
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
相关资源
最近更新 更多