Sub topic 9
Cleaning up when the view goes away
This chapter assumes you have already built a platform view on both platforms: a PlatformViewFactory on Android, a FlutterPlatformViewFactory on iOS, and an AndroidView or UiKitView in Dart. It also assumes you can read basic Kotlin and Swift and have used a MethodChannel. Here you will learn what the framework cleans up for you, what you must clean up yourself, and how to check that nothing leaks.
What disposal means for a platform view
A platform view has two halves. The Dart half is a widget and a controller. The native half is a view object, plus anything that object created: timers, listeners, channels, media players, network requests. When the widget leaves the tree, the framework tells the engine to dispose the native view. It does not know what your native code started, so it cannot stop those things for you.
If your native view starts a repeating timer and never stops it, the timer keeps firing after the user has left the screen. The timer also keeps the view alive, so a new copy of the view is added every time the screen is opened. Cleanup is where most platform view memory leaks come from.
The sequence looks like this:
When the framework disposes a view
The view lives exactly as long as the Dart widget's State object. That has consequences you can test:
- Removing the widget from a parent, for example with
if (show) NativeCounter(), disposes the view. - Popping the route that contains the view disposes it.
- Pushing a new route on top of the page does not dispose it. The page below stays in the tree, so its native view and any timers keep running.
- A view inside a
ListViewitem is disposed when the item scrolls far enough off screen to be recycled. When the user scrolls back, a new native view is created with a new view id, and any state in the old one is gone. - Wrapping the item in
AutomaticKeepAliveClientMixinkeeps the view alive off screen. You trade lost state for memory, and any native work keeps running, so use it sparingly.
Treat the view id as belonging to one instance. Do not store it somewhere that outlives the widget and assume it still points to a live view.
Android: implement `dispose()`
PlatformView.dispose() is the one cleanup hook on Android. The framework calls it once, when the view is no longer needed, and you must not use the view afterwards.
Put anything that could outlive the view in dispose():
- Callbacks posted to a
Handler. - Listeners registered on system services or other objects.
- The
MethodChannelhandler for this view. - Native SDK objects with their own teardown, such as players, camera sessions and map views that need an
onDestroycall.
Here is a counter view that increments once per second and supports a reset call. The factory receives the engine's BinaryMessenger so each view can open its own channel.
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.TextView
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
class NativeCounter(
context: Context,
messenger: BinaryMessenger,
viewId: Int
) : PlatformView, MethodChannel.MethodCallHandler {
private val handler = Handler(Looper.getMainLooper())
private val textView = TextView(context).apply { textSize = 20f }
private val channel =
MethodChannel(messenger, "com.example.app/native_counter/$viewId")
private var count = 0
private val tick = object : Runnable {
override fun run() {
count++
render()
handler.postDelayed(this, 1000)
}
}
init {
render()
channel.setMethodCallHandler(this)
handler.postDelayed(tick, 1000)
}
private fun render() {
textView.text = "Count: $count"
}
override fun getView(): View = textView
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"reset" -> {
count = 0
render()
result.success(null)
}
else -> result.notImplemented()
}
}
override fun dispose() {
handler.removeCallbacks(tick)
channel.setMethodCallHandler(null)
}
}
class NativeCounterFactory(private val messenger: BinaryMessenger) :
PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView =
NativeCounter(context, messenger, viewId)
}
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.platformViewsController.registry.registerViewFactory(
"com.example.app/native_counter",
NativeCounterFactory(flutterEngine.dartExecutor.binaryMessenger)
)
}
}Without the removeCallbacks(tick) line, the main looper keeps a reference to the Runnable. The Runnable references the view, and the view references the Context. The Context can be the activity, so a leaked view can keep a whole activity in memory.
Two more habits help on Android:
- Do not store the
Contextor the view in a static field or a singleton. PlatformViewhas optional methods such asonFlutterViewAttached(View)andonFlutterViewDetached(). If you keep the Flutter view you receive in the first one, clear it in the second.
iOS: there is no `dispose()`
FlutterPlatformView has no disposal method. The engine drops its reference to your object, and Swift's reference counting then runs deinit. Cleanup on iOS is therefore a matter of two things: making sure the object can actually be released, and doing teardown in deinit.
The main cause of a leaked iOS platform view is a retain cycle. A channel handler closure that captures self strongly is held by the messenger, so the view is never released. Capture self weakly:
import Flutter
import UIKit
class NativeCounterFactory: NSObject, FlutterPlatformViewFactory {
private let messenger: FlutterBinaryMessenger
init(messenger: FlutterBinaryMessenger) {
self.messenger = messenger
super.init()
}
func create(
withFrame frame: CGRect,
viewIdentifier viewId: Int64,
arguments args: Any?
) -> FlutterPlatformView {
return NativeCounter(frame: frame, viewId: viewId, messenger: messenger)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}
class NativeCounter: NSObject, FlutterPlatformView {
private let label = UILabel()
private let channel: FlutterMethodChannel
private var timer: Timer?
private var count = 0
init(frame: CGRect, viewId: Int64, messenger: FlutterBinaryMessenger) {
channel = FlutterMethodChannel(
name: "com.example.app/native_counter/\(viewId)",
binaryMessenger: messenger
)
super.init()
label.frame = frame
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 20)
render()
channel.setMethodCallHandler { [weak self] call, result in
guard let self = self else {
result(FlutterMethodNotImplemented)
return
}
if call.method == "reset" {
self.count = 0
self.render()
result(nil)
} else {
result(FlutterMethodNotImplemented)
}
}
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
guard let self = self else { return }
self.count += 1
self.render()
}
}
private func render() {
label.text = "Count: \(count)"
}
func view() -> UIView {
return label
}
deinit {
timer?.invalidate()
channel.setMethodCallHandler(nil)
}
}
// In AppDelegate.application(_:didFinishLaunchingWithOptions:), after
// GeneratedPluginRegistrant.register(with: self):
//
// let registrar = self.registrar(forPlugin: "NativeCounterPlugin")!
// registrar.register(
// NativeCounterFactory(messenger: registrar.messenger()),
// withId: "com.example.app/native_counter"
// )The run loop retains a scheduled Timer until it is invalidated, so [weak self] alone would leave a timer firing forever with nothing to update. The invalidate() call in deinit stops it. The [weak self] in the handler is what lets deinit run in the first place.
The Dart side: stop using the channel
The Dart MethodChannel object is only a name and a codec, so it holds no native resource. The risks on the Dart side are different:
- Calling the native view after it has been disposed. A call to a channel whose native handler is cleared completes with a
MissingPluginException, so catch it if a late call is possible. - Handlers you registered for native-to-Dart calls, which should be cleared so late messages are not delivered to a dead
State. - Calling
setStateafter disposal.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class NativeCounterView extends StatefulWidget {
const NativeCounterView({super.key});
@override
State<NativeCounterView> createState() => _NativeCounterViewState();
}
class _NativeCounterViewState extends State<NativeCounterView> {
static const String viewType = 'com.example.app/native_counter';
MethodChannel? _channel;
void _onPlatformViewCreated(int id) {
_channel = MethodChannel('$viewType/$id');
}
Future<void> _reset() async {
final channel = _channel;
if (channel == null) return;
try {
await channel.invokeMethod<void>('reset');
} on MissingPluginException {
// The native view was disposed before the call arrived.
}
}
@override
void dispose() {
_channel?.setMethodCallHandler(null);
_channel = null;
super.dispose();
}
Widget _nativeView() {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return AndroidView(
viewType: viewType,
onPlatformViewCreated: _onPlatformViewCreated,
);
case TargetPlatform.iOS:
return UiKitView(
viewType: viewType,
onPlatformViewCreated: _onPlatformViewCreated,
);
default:
return const Text('Native view is not supported on this platform');
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(height: 120, child: _nativeView()),
ElevatedButton(onPressed: _reset, child: const Text('Reset')),
],
);
}
}The widgets AndroidView and UiKitView own their controllers and dispose them when they leave the tree. You do not call anything on them yourself.
A cleanup checklist
| Resource | Android (`dispose()`) | iOS (`deinit`) |
|---|---|---|
| Repeating work | `handler.removeCallbacks(...)`, cancel executors | `timer.invalidate()`, cancel `DispatchSourceTimer` |
| Channel handler | `channel.setMethodCallHandler(null)` | `channel.setMethodCallHandler(nil)` |
| Closures that call back into the view | Avoid inner classes that outlive the view | Capture `[weak self]` |
| Observers and listeners | Unregister from the system service or object | Remove `NotificationCenter` observers and KVO |
| SDK objects | Call their own `release`, `destroy` or `onDestroy` | Call their own `stop`, `invalidate` or `close` |
| Context or view references | Never in statics or singletons | Avoid strong references from long-lived objects |
Verifying that cleanup happens
Do not assume cleanup works. Test it:
- Add a log line to
dispose()on Android and todeiniton iOS. Show and hide the widget and confirm the line prints each time. - If the line never prints on iOS, look for a retain cycle, usually a closure that captures
selfstrongly. - Open and close the screen ten times, then check memory. In Android Studio, use the Memory Profiler and look for multiple live instances of your view class. On iOS, use Xcode's Memory Graph Debugger to look for the same.
- Check for background work. A counter that keeps logging after the screen is closed has a timer you did not stop.
Common mistakes
- Doing cleanup in the factory instead of in the view. The factory lives for the whole engine and sees no per-view events.
- Assuming a pushed route disposes the page below it. It does not, so timers keep running under the new page.
- Clearing the handler but forgetting the timer, or the reverse. Both must be stopped.
- Keeping a strong reference to the
Contextthatcreatereceives, in a place that outlives the view. - Calling
result.successon a disposed native view after a long task. Cancel the task in cleanup, or check a disposed flag before replying.
Exercise
A screen shows the iOS NativeCounter. You push a settings route on top of it, wait ten seconds, then pop back. Does the native timer run while the settings route is visible? What would you change if the counter should pause there?
Show answer
Yes. Pushing a route does not remove the page below from the widget tree, so the State is not disposed and the native view is not released. Its timer keeps running. To pause it, either add native pause and resume methods and call them over the per-view channel when the route changes (for example from a RouteAware callback), or conditionally remove the widget from the tree, which disposes the view and loses its state.
Exercise
An iOS platform view logs nothing in deinit after its widget is removed. The view registers a channel handler as channel.setMethodCallHandler { call, result in self.handle(call, result) }. What is wrong and how do you fix it?
Show answer
The closure captures self strongly. The messenger holds the handler, so the view always has an owner and deinit never runs. Capture weakly with [weak self] and unwrap with guard let self = self, replying FlutterMethodNotImplemented if it is nil. Then clear the handler and invalidate any timers in deinit.
Exercise
On Android, which three things should NativeCounter.dispose() do or avoid so the view can be garbage collected, and why does a leaked Runnable matter more than its size suggests?
Show answer
It should remove pending Handler callbacks, clear the channel's method call handler, and avoid leaving the view or its Context in any static or long-lived reference. A posted Runnable that references the view is held by the main looper, and the view holds the Context, which may be the activity. One forgotten callback can therefore keep an entire activity in memory.