darteventsevent-handling

Event and EventHandle in Dart


I'm coming from C# and I understand (more or less) the logic around the Events and how they works. Now, I have to traduce an event paradigm (with data passing) from C# to Dart but I don't understand how it works on Dart. Can anyone explain to me patiently? Thanks

EDIT: These are the pieces of code that i have to translate

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);
};

[...]

and EngineComputationEventArgs.cs

public class EngineComputationEventArgs : EventArgs {

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

    public Result Result { get; private set; }

}

Solution

  • Dart does not have built in "Event" types like C# does. You usually use a Stream as event emitter, and a corresponding StreamController to add events to it.

    Example:

    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));
        }
      }
    }
    

    You then add listeners by listening on the stream:

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

    or

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

    Your "args" class could be (since I know nothing about EventArgs)

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