Flutter typedef 函数类型

typedef 函数 在flutter中的应用:

实际上在使用 flutter 的时候经常会用到这个东西:比如 IconButton 组件里面 onPressed

复制代码
IconButton(
  onPressed: () {},
  icon: Icon(Icons.add),
),

到 onPressed 定义的地方: VoidCallback

复制代码
/// The callback that is called when the button is tapped or otherwise activated.
///
/// If this is set to null, the button will be disabled.
final VoidCallback? onPressed;

到 VoidCallback 定义的地方: 发现是一个 typedef 类型

复制代码
/// Signature of callbacks that have no arguments and return no data.
typedef VoidCallback = void Function();

其实 flutter 还有很多类型的东西:

复制代码
typedef VoidCallback        = void Function();
typedef ValueChanged<T>     = void Function(T value);
typedef ValueSetter<T>      = void Function(T value);
typedef ValueGetter<T>      = T Function();
typedef IterableFilter<T>   = Iterable<T> Function(Iterable<T> input);
typedef AsyncCallback       = Future<void> Function();
typedef AsyncValueSetter<T> = Future<void> Function(T value);

上面都是 Flutter 自带的一些 typedef 函数,当然你也可以自定义。不过使用他自带的其实也都够用了!

复制代码
typedef Compare<T> = int Function(T a, T b);

因为 typedef 是一个类型, 所以他可以使用 is 方法判断函数是不是你自己定义的:

复制代码
typedef Compare<T> = int Function(T a, T b);

int sort(Object a, Object b) => 0;


class SortedCollection {
  Compare compare;

  SortedCollection(this.compare);
}

void main() {
  SortedCollection coll = SortedCollection(sort);
  printf(coll.compare is Function); //false
  printf(coll.compare is Compare);  //TRUE
}
typedef 自定义函数

自定义其他 多参数的情况:

复制代码
typedef VoidCallback = void Function();
typedef ErrorCallback = void Function(int code, String error);
typedef V2TimUserFullInfoCallback = void Function(V2TimUserFullInfo info);
typedef OnTotalUnreadMessageCountChanged = void Function(int totalUnreadCount);
typedef OnUserStatusChanged = void Function(
    List<V2TimUserStatus> userStatusList);
typedef OnLog = void Function(int logLevel, String logContent);
typedef OnRecvC2CTextMessageCallback = void Function(
  String msgID,
  V2TimUserInfo userInfo,
  String text,
);
typedef OnRecvMessageExtensionsChanged = void Function(
  String msgID,
  List<V2TimMessageExtension> extensions,
);
typedef OnRecvMessageExtensionsDeleted = void Function(
  String msgID,
  List<String> extensionKeys,
);
typedef OnMessageDownloadProgressCallback = void Function(
  V2TimMessageDownloadProgress messageProgress,
);
typedef OnRecvC2CCustomMessageCallback = void Function(
  String msgID,
  V2TimUserInfo sender,
  String customData,
);
typedef OnRecvGroupTextMessageCallback = void Function(
  String msgID,
  String groupID,
  V2TimGroupMemberInfo sender,
  String text,
);

typedef OnRecvGroupCustomMessageCallback = void Function(
  String msgID,
  String groupID,
  V2TimGroupMemberInfo sender,
  String customData,
);
typedef OnMemberEnterCallback = void Function(
  String groupID,
  List<V2TimGroupMemberInfo> memberList,
);
// void 	onMemberEnter (String groupID, List< V2TIMGroupMemberInfo > memberList)
typedef OnMemberLeaveCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo member,
);
// void 	onMemberLeave (String groupID, V2TIMGroupMemberInfo member)
typedef OnMemberInvitedCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
  List<V2TimGroupMemberInfo> memberList,
);
// void 	onMemberInvited (String groupID, V2TIMGroupMemberInfo opUser, List< V2TIMGroupMemberInfo > memberList)
typedef OnMemberKickedCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
  List<V2TimGroupMemberInfo> memberList,
);
// void 	onMemberKicked (String groupID, V2TIMGroupMemberInfo opUser, List< V2TIMGroupMemberInfo > memberList)
typedef OnMemberInfoChangedCallback = void Function(
  String groupID,
  List<V2TimGroupMemberChangeInfo> v2TIMGroupMemberChangeInfoList,
);
// void 	onMemberInfoChanged (String groupID, List< V2TIMGroupMemberChangeInfo > v2TIMGroupMemberChangeInfoList)
typedef OnGroupCreatedCallback = void Function(
  String groupID,
);
// void 	onGroupCreated (String groupID)
typedef OnGroupDismissedCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
);
// void 	onGroupDismissed (String groupID, V2TIMGroupMemberInfo opUser)
typedef OnGroupRecycledCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
);
// void 	onGroupRecycled (String groupID, V2TIMGroupMemberInfo opUser)
typedef OnGroupInfoChangedCallback = void Function(
  String groupID,
  List<V2TimGroupChangeInfo> changeInfos,
);
// void 	onGroupInfoChanged (String groupID, List< V2TIMGroupChangeInfo > changeInfos)
typedef OnReceiveJoinApplicationCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo member,
  String opReason,
);
// void 	onReceiveJoinApplication (String groupID, V2TIMGroupMemberInfo member, String opReason)
typedef OnApplicationProcessedCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
  bool isAgreeJoin,
  String opReason,
);
// void 	onApplicationProcessed (String groupID, V2TIMGroupMemberInfo opUser, boolean isAgreeJoin, String opReason)
typedef OnGrantAdministratorCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
  List<V2TimGroupMemberInfo> memberList,
);
// void 	onGrantAdministrator (String groupID, V2TIMGroupMemberInfo opUser, List< V2TIMGroupMemberInfo > memberList)
typedef OnRevokeAdministratorCallback = void Function(
  String groupID,
  V2TimGroupMemberInfo opUser,
  List<V2TimGroupMemberInfo> memberList,
);
// void 	onRevokeAdministrator (String groupID, V2TIMGroupMemberInfo opUser, List< V2TIMGroupMemberInfo > memberList)
typedef OnQuitFromGroupCallback = void Function(
  String groupID,
);
// void 	onQuitFromGroup (String groupID)
typedef OnReceiveRESTCustomDataCallback = void Function(
  String groupID,
  String customData,
);
// void 	onReceiveRESTCustomData (String groupID, byte[] customData)
typedef OnGroupAttributeChangedCallback = void Function(
  String groupID,
  Map<String, String> groupAttributeMap,
);
// void 	onGroupAttributeChanged (String groupID, Map< String, String > groupAttributeMap)
typedef OnRecvNewMessageCallback = void Function(
  V2TimMessage msg,
);

// void 	onGroupAttributeChanged (String groupID, Map< String, String > groupAttributeMap)
typedef OnRecvMessageModified = void Function(
  V2TimMessage msg,
);

// void 	onRecvNewMessage (V2TIMMessage msg)
typedef OnRecvC2CReadReceiptCallback = void Function(
  List<V2TimMessageReceipt> receiptList,
);
// void 	onRecvC2CReadReceipt (List< V2TIMMessageReceipt > receiptList)
typedef OnRecvMessageRevokedCallback = void Function(
  String msgID,
);
// void 	onRecvMessageRevoked (String msgID)
//
typedef OnFriendApplicationListAddedCallback = void Function(
  List<V2TimFriendApplication> applicationList,
);
// void 	onFriendApplicationListAdded (List< V2TIMFriendApplication > applicationList)
typedef OnFriendApplicationListDeletedCallback = void Function(
  List<String> userIDList,
);
// void 	onFriendApplicationListDeleted (List< String > userIDList)
typedef OnFriendApplicationListReadCallback = void Function();
// void 	onFriendApplicationListRead ()
typedef OnFriendListAddedCallback = void Function(List<V2TimFriendInfo> users);
// void 	onFriendListAdded (List< V2TIMFriendInfo > users)
typedef OnFriendListDeletedCallback = void Function(List<String> userList);
// void 	onFriendListDeleted (List< String > userList)
typedef OnBlackListAddCallback = void Function(List<V2TimFriendInfo> infoList);
// void 	onBlackListAdd (List< V2TIMFriendInfo > infoList)
typedef OnBlackListDeletedCallback = void Function(List<String> userList);
// void 	onBlackListDeleted (List< String > userList)
typedef OnFriendInfoChangedCallback = void Function(
  List<V2TimFriendInfo> infoList,
);
// void 	onFriendInfoChanged (List< V2TIMFriendInfo > infoList)
typedef OnConversationChangedCallback = void Function(
  List<V2TimConversation> conversationList,
);
// void 	onNewConversation (List< V2TIMConversation > conversationList)
typedef OnNewConversation = void Function(
  List<V2TimConversation> conversationList,
);

// void 	onConversationChanged (List< V2TIMConversation > conversationList)
typedef OnReceiveNewInvitationCallback = void Function(
  String inviteID,
  String inviter,
  String groupID,
  List<String> inviteeList,
  String data,
);
// void 	onReceiveNewInvitation (String inviteID, String inviter, String groupID, List< String > inviteeList, String data)
typedef OnInviteeAcceptedCallback = void Function(
  String inviteID,
  String invitee,
  String data,
);
// void 	onInviteeAccepted (String inviteID, String invitee, String data)
typedef OnInviteeRejectedCallback = void Function(
  String inviteID,
  String invitee,
  String data,
);
// void 	onInviteeRejected (String inviteID, String invitee, String data)
typedef OnInvitationCancelledCallback = void Function(
  String inviteID,
  String inviter,
  String data,
);
// void 	onInvitationCancelled (String inviteID, String inviter, String data)
typedef OnInvitationTimeoutCallback = void Function(
  String inviteID,
  List<String> inviteeList,
);
// void 	onInvitationTimeout (String inviteID, List< String > inviteeList)
//
typedef OnSendMessageProgressCallback = void Function(
  V2TimMessage message,
  int progress,
);
typedef OnRecvMessageReadReceipts = void Function(
  List<V2TimMessageReceipt> receiptList,
);
typedef OnConversationGroupCreated = void Function(
    String groupName, List<V2TimConversation> conversationList);

typedef OnConversationGroupDeleted = void Function(String groupName);

typedef OnConversationGroupNameChanged = void Function(
    String oldName, String newName);

typedef OnConversationsAddedToGroup = void Function(
    String groupName, List<V2TimConversation> conversationList);

typedef OnConversationsDeletedFromGroup = void Function(
    String groupName, List<V2TimConversation> conversationList);

typedef OnTopicCreated = void Function(String groupID, String topicID);

typedef OnTopicDeleted = void Function(
    String groupID, List<String> topicIDList);

typedef OnTopicInfoChanged = void Function(
    String groupID, V2TimTopicInfo topicInfo);

typedef OnGroupCounterChanged = void Function(
  String groupID,
  String key,
  int newValue,
);
typedef 函数 实践:

按照使用的场景,最多出现的地方就是我们的 回调函数,不管是按钮的,还是其他的地方,和其他语言的回调函数类似:

  • javascript Function, 箭头函数
  • c# 事件和委托

都是可以 把函数 当做参数传递,然后在另外一个地方等待调用。

typedef 函数 高阶用法示例:

► 腾讯 im中的 使用 typedef 实例

复制代码
  @override
  Future<bool?> init(
      {
      /// Callback from TUIKit invoke, includes IM SDK API error, notify information, Flutter error.
      ValueChanged<TIMCallback>? onTUIKitCallbackListener,
      required int sdkAppID,
      required LogLevelEnum loglevel,
      required V2TimSDKListener listener,
      LanguageEnum? language,
      String? extraLanguage,
      TIMUIKitConfig? config,

      /// Specify the current device platform, mobile or desktop, based on your needs.
      /// TUIKit will automatically determine the platform if no specification is provided. DeviceType? platform,
      DeviceType? platform,
      VoidCallback? onWebLoginSuccess}) async {
    省略
}
复制代码
 V2TimSDKListener  listener  定义如下  
复制代码
class V2TimSDKListener {
  VoidCallback onConnecting = () {};
  VoidCallback onConnectSuccess = () {};
  ErrorCallback onConnectFailed = (int code, String error) {};
  VoidCallback onKickedOffline = () {};
  VoidCallback onUserSigExpired = () {};
  V2TimUserFullInfoCallback onSelfInfoUpdated = (
    V2TimUserFullInfo info,
  ) {};
  OnUserStatusChanged onUserStatusChanged = (List<V2TimUserStatus> userStatusList){};
  OnLog onLog = (int logLevel,String logContent){
    
  };


  V2TimSDKListener({
    ErrorCallback? onConnectFailed,
    VoidCallback? onConnectSuccess,
    VoidCallback? onConnecting,
    VoidCallback? onKickedOffline,
    V2TimUserFullInfoCallback? onSelfInfoUpdated,
    VoidCallback? onUserSigExpired,
    OnUserStatusChanged? onUserStatusChanged,
    OnLog? onLog,
  }) {
    if (onConnectFailed != null) {
      this.onConnectFailed = onConnectFailed;
    }
    if (onConnectSuccess != null) {
      this.onConnectSuccess = onConnectSuccess;
    }
    if (onConnecting != null) {
      this.onConnecting = onConnecting;
    }
    if (onKickedOffline != null) {
      this.onKickedOffline = onKickedOffline;
    }
    if (onSelfInfoUpdated != null) {
      this.onSelfInfoUpdated = onSelfInfoUpdated;
    }
    if (onUserSigExpired != null) {
      this.onUserSigExpired = onUserSigExpired;
    }
    if(onUserStatusChanged!=null){
      this.onUserStatusChanged = onUserStatusChanged;
    }
    if(onLog!=null){
      this.onLog = onLog;
    }
  }
}

他的嵌套使用很普遍,甚至直接 定义一个类型来接收 回调函数:合理使用的情况下,会给我们代码提供很大便捷

相关推荐
程序员老刘9 小时前
跨平台开发地图 | 2026年11月
flutter·ai编程·客户端
传奇开心果编程16 小时前
【Flutter踩坑排雷】第30课:异常未捕获坑|未捕获异常直接闪退,全局兜底故障处理
android·flutter·ios·移动开发·dart·ui框架·声明式ui
恋猫de小郭17 小时前
Flutter Native Interop 稳定了,Platform Channel 要退场了
android·前端·flutter
好的佩奇1 天前
Dart 之可迭代对象与生成器
android·flutter·dart
恋猫de小郭2 天前
Flutter Analyzer 系列坑推进,必看,AI 时代这玩意最吃你内存
android·前端·flutter
LinXunFeng2 天前
拿竞品 App 一扫,技术栈全暴露了
android·flutter·开源
传奇开心果编程3 天前
【Flutter踩坑排雷】第28课:平台目录缺失与修复坑|`flutter create` 的“重建”与“覆盖”边界
android·flutter·ios·移动开发·跨平台·dart·声明式ui
程序员老刘·3 天前
Flutter 3.50更新,开发者应该关注什么?
flutter·ai编程·跨平台开发
传奇开心果编程4 天前
【Flutter踩坑排雷】第25课:ScrollController 误用坑|跳转失效、监听泄漏与“控制器未附加”
android·flutter·ios·移动开发·跨平台·dart·声明式ui
程序员老刘4 天前
Flutter 3.50更新,开发者应该关注什么?
flutter·ai编程·客户端