You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dash及Dart中是否存在C# EventHandler与委托的等价实现?

Equivalent of C# EventHandler in Dart/Flutter

Hey there! As someone who’s made the jump from C# to Flutter, I totally get wanting to carry over that familiar event-driven pattern using EventHandlers and delegates. Good news—Dart has several ways to replicate this functionality, let’s break them down:

1. Using Typedefs & Function References (Closest to C# Delegates/EventHandler)

Dart doesn’t have a built-in EventHandler type like C#, but you can create your own using typedef to define a function signature (just like a C# delegate). Then you can attach and invoke functions matching that signature, mirroring how you’d work with C# events.

Example:

First, define a typedef that matches C#'s EventHandler<T> signature:

typedef void EventHandler<T>(Object? sender, T eventArgs);

Then build a class with event-like behavior, including methods to subscribe, unsubscribe, and trigger the event:

class NotificationCenter {
  // Store subscribed handlers (supports multicast with + operator)
  EventHandler<String>? _onNotificationSent;

  // Subscribe to the event
  void addNotificationHandler(EventHandler<String> handler) {
    // For single subscriber:
    _onNotificationReceived = handler;
    // For multiple subscribers (multicast):
    // _onNotificationReceived ??= (_, __) {};
    // _onNotificationReceived = _onNotificationReceived! + handler;
  }

  // Unsubscribe from the event
  void removeNotificationHandler(EventHandler<String> handler) {
    // For multicast:
    // _onNotificationReceived = _onNotificationReceived! - handler;
  }

  // Trigger the event internally
  void _sendNotification(String message) {
    _onNotificationReceived?.call(this, message);
  }

  // Public method to trigger the event
  void publishNotification(String message) {
    print("Publishing notification: $message");
    _sendNotification(message);
  }
}

Usage:

void main() {
  final center = NotificationCenter();
  
  // Subscribe to the event
  center.addNotificationHandler((sender, message) {
    print("Got notification from $sender: $message");
  });
  
  // Trigger the event
  center.publishNotification("Hello from Dart!");
}

Note: For multicast support (multiple subscribers), Dart lets you combine functions with the + operator (and remove them with -), just like C# multicast delegates.

2. Using Streams (Dart’s Preferred Event Pattern)

For more robust, asynchronous event handling (especially in Flutter), Dart’s Stream is the idiomatic choice. It’s similar to C#'s IObservable but deeply integrated into the language, perfect for scenarios with multiple subscribers, error handling, or async event flows.

Example with StreamController:

import 'dart:async';

class ChatService {
  // Broadcast controller allows multiple subscribers
  final _messageController = StreamController<String>.broadcast();
  
  // Expose the stream for external subscribers
  Stream<String> get onNewMessage => _messageController.stream;
  
  // Send a message to the stream (triggers the event)
  void sendMessage(String message) {
    print("Sending chat message: $message");
    _messageController.add(message);
  }
  
  // Clean up to avoid memory leaks (critical in Flutter)
  void dispose() {
    _messageController.close();
  }
}

Usage:

void main() {
  final chat = ChatService();
  
  // Subscribe to the stream
  final subscription = chat.onNewMessage.listen((message) {
    print("Received chat message: $message");
  });
  
  // Send a message
  chat.sendMessage("Hey, how's Flutter treating you?");
  
  // Don't forget to cancel subscriptions when done!
  subscription.cancel();
  chat.dispose();
}

In Flutter, this pairs perfectly with StreamBuilder to update UI automatically when events fire—super handy for real-time features like chat or notifications.

Key Takeaways

  • If you want a direct 1:1 match to C#'s EventHandler, use typedef with function references (supports multicast).
  • For most Dart/Flutter projects, Stream is the better approach—it’s built for async work, integrates seamlessly with the framework, and handles multiple subscribers out of the box.

Hope this helps you bring that familiar event-driven workflow to your Flutter projects! 😊

内容的提问来源于stack exchange,提问作者KingLagalot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:41:47