Sub topic 9
Cleaning Up When the View Goes Away
Assume you know Flutter widget lifecycles, basic MethodChannel use, and simple Kotlin and Swift. A platform view has two lifecycles to coordinate:
- Flutter creates and removes the widget.
- Android or iOS creates and releases the native view.
Cleanup matters because a native view can hold memory, timers, listeners, camera sessions, or channel handlers after it disappears from the screen.
The platform view lifecycle
Flutter creates a platform view when its AndroidView or UiKitView enters the widget tree. The native factory creates the corresponding native object. When Flutter removes the widget, the platform side receives a disposal request.
The main lifecycle looks like this:
On Android, implement PlatformView.dispose(). Flutter calls this method when it no longer needs the view. Use it to stop work and release references.
On iOS, FlutterPlatformView does not define a dispose method. Native cleanup normally happens in deinit, when the object is released. You can also provide an explicit cleanup method if the view owns resources that must stop before deallocation.
Cleaning up on Android
Suppose a native view owns a timer and a channel. The timer must stop, and the channel handler must no longer respond after disposal.
class NativeCounter(
private val context: Context,
private val viewId: Int
) : PlatformView {
private val textView = TextView(context)
private val handler = Handler(Looper.getMainLooper())
private val channel = MethodChannel(
FlutterMainActivity.engine?.dartExecutor?.binaryMessenger,
"com.example.app/native_counter/$viewId"
)
private val ticker = object : Runnable {
override fun run() {
textView.text = System.currentTimeMillis().toString()
handler.postDelayed(this, 1000)
}
}
init {
channel.setMethodCallHandler { call, result ->
when (call.method) {
"reset" -> {
textView.text = "0"
result.success(null)
}
else -> result.notImplemented()
}
}
handler.post(ticker)
}
override fun getView(): View = textView
override fun dispose() {
handler.removeCallbacks(ticker)
channel.setMethodCallHandler(null)
}
}The channel setup in a real app should receive a valid BinaryMessenger from the activity, plugin, or factory rather than using a global engine reference. The important lifecycle rule is that every resource started by the view has a matching cleanup action.
Common Android cleanup actions include:
- Stop handlers, coroutines, timers, and animations.
- Unregister broadcast receivers and lifecycle observers.
- Remove listeners from parent views.
- Stop camera, microphone, map, or video sessions.
- Clear the
MethodChannelhandler. - Release references to an activity or context when they are no longer needed.
Cleaning up on iOS
Swift uses object ownership instead of an explicit platform-view disposal method. Put cleanup in deinit or in a dedicated method called by a channel before the view is discarded.
final class NativeCounter: NSObject, FlutterPlatformView {
private let label: UILabel
private var timer: Timer?
init(frame: CGRect, arguments args: Any?) {
label = UILabel(frame: frame)
super.init()
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
[weak self] _ in
self?.label.text = Date().description
}
}
func view() -> UIView {
return label
}
deinit {
timer?.invalidate()
timer = nil
NotificationCenter.default.removeObserver(self)
}
}Use weak references in timer and callback closures when appropriate. A closure that strongly captures the view can keep the view alive, preventing deinit from running.
Cleaning up Dart state
A Dart widget can also own a channel or other resources. Clear those resources in State.dispose().
@override
void dispose() {
_channel?.setMethodCallHandler(null);
_channel = null;
super.dispose();
}Do not assume that hiding a platform view cleans it up. A widget kept in an Offstage, inactive tab, or cached route can remain mounted. Dispose occurs when the widget is actually removed from the tree.
A practical cleanup checklist
Before shipping a platform view, verify that:
- Every native timer, listener, and session has a stop operation.
- Android implements
PlatformView.dispose(). - iOS releases resources in
deinitor an explicit cleanup method. - Dart clears channel handlers in
State.dispose(). - Callbacks use weak references where a retain cycle is possible.
- Rebuilding the widget does not create duplicate listeners.
- Removing and re-adding the widget does not leave stale native state.
Exercise
A camera preview remains active after its Flutter page is popped. Which lifecycle method should you inspect first on Android, and what should it do?
Show answer
Inspect PlatformView.dispose(). It should stop the camera session, unregister listeners, stop timers or callbacks, clear channel handlers, and release other resources owned by the native view.