Flutter dispose MethodChannel

Viewed 883

Is there a way to dispose a MethodChannel / EventChannel when there is no need for it? I am asking because i want to create multiple method/event channels for objects.

Example:

class Call {
 ... fields ...
 MethodChannel channel;

 Future<void> answer() {
   return channel.invokeMethod('@answer')
 }
}

For each Call object i want it to have its own channel, so i can send messages to the native part without having 1 method channel that handles all the logic of the calls.

Is it recommended to use 1 channel?

Thanks.

1 Answers

The channel itself is just a wrapper around a name with convenient methods to work with BinaryMessenger. Only when you set a callback with setMethodCallHandler that the callback (and likely your object) is hold by the messenger, and you must call setMethodCallHandler again with null for it to release your object.

Thus, you can create and use as many as channels you want, as long as they have different names, no dispose needed. However, when you listen to method call with channel.setMethodCallHandler(yourCallback), you need to call channel.setMethodCallHandler(null) when you are done to avoid leaking your callback.

Related