Sub topic 16
Threading, Engine Lifecycle, and Resource Cleanup
Assume intermediate Dart and Flutter skills, including Future, Stream, StatefulWidget, and dispose(). Also assume basic Kotlin or Swift knowledge. This chapter focuses on what happens when a channel crosses threads and when a Flutter engine starts or stops.
Understand the lifecycle
A Flutter platform channel belongs to a Flutter engine. The engine connects Dart code to native code through a binary messenger. Register handlers when the engine is configured, not every time a widget rebuilds.
An EventChannel has a second lifecycle. Native code starts producing events after Dart subscribes. It should stop producing them when the subscription is canceled. Otherwise, a sensor listener, timer, or location provider can continue running after the screen disappears.
Keep work on suitable threads
A channel call is asynchronous from Dart's perspective, but native work still consumes native threads.
- Return quickly from the native handler when possible.
- Move network, database, file, or sensor setup work to an appropriate background mechanism.
- Send the final result through the channel's result callback.
- Do UI work only on the platform's UI thread.
- Do not assume that a stream event means the receiving widget still exists.
The exact threading API differs between Android and iOS. Follow each platform's rules for dispatching UI updates and canceling background work.
Pair every resource with cleanup
Store a Dart stream subscription and cancel it in dispose(). Guard callbacks that can finish after disposal. The native onCancel handler must release the matching resource.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
class SensorView extends StatefulWidget {
const SensorView({super.key});
@override
State<SensorView> createState() => _SensorViewState();
}
class _SensorViewState extends State<SensorView> {
static const _sensorChannel = EventChannel('com.example.app/sensor');
StreamSubscription<dynamic>? _subscription;
double? _value;
@override
void initState() {
super.initState();
_subscription = _sensorChannel.receiveBroadcastStream().listen(
(value) {
if (!mounted) return;
setState(() => _value = (value as num).toDouble());
},
onError: (Object error, StackTrace stack) {
if (!mounted) return;
setState(() => _value = null);
},
);
}
@override
void dispose() {
_subscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text(_value == null ? 'No reading' : '${_value!}');
}
}mounted prevents a late event from calling setState() after the widget has been removed. It does not replace cancellation. Cancellation tells Dart and native code that the listener is no longer needed.
Handle engine changes
An application may create more than one engine, and a host activity or view controller can be recreated. Keep channel names and message contracts stable. Tie native resources to the engine or host lifecycle that owns them. On engine detachment, remove handlers and release resources that cannot outlive that engine.
Exercise
A widget receives sensor events after navigation and logs a “setState called after dispose” error. What two changes should you make?
Show answer
Cancel the Dart stream subscription in dispose(), and stop the native sensor listener from the EventChannel onCancel handler.