Skip to content

Commit

Permalink
AppLifecycleListener should dispatch creation and disposal events. (#…
Browse files Browse the repository at this point in the history
…137840)
  • Loading branch information
ksokolovskyi authored Nov 3, 2023
1 parent 8375dfd commit 2369897
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
14 changes: 14 additions & 0 deletions packages/flutter/lib/src/widgets/app_lifecycle_listener.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable {
this.onStateChange,
}) : binding = binding ?? WidgetsBinding.instance,
_lifecycleState = (binding ?? WidgetsBinding.instance).lifecycleState {
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
MemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/widgets.dart',
className: '$AppLifecycleListener',
object: this,
);
}
this.binding.addObserver(this);
}

Expand Down Expand Up @@ -174,6 +183,11 @@ class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable {
@mustCallSuper
void dispose() {
assert(_debugAssertNotDisposed());
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
MemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
binding.removeObserver(this);
assert(() {
_debugDisposed = true;
Expand Down
15 changes: 13 additions & 2 deletions packages/flutter/test/widgets/app_lifecycle_listener_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';

void main() {
late AppLifecycleListener listener;
AppLifecycleListener? listener;

Future<void> setAppLifeCycleState(AppLifecycleState state) async {
final ByteData? message = const StringCodec().encodeMessage(state.toString());
Expand Down Expand Up @@ -40,7 +40,8 @@ void main() {
});

tearDown(() {
listener.dispose();
listener?.dispose();
listener = null;
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance;
binding.resetLifecycleState();
binding.platformDispatcher.resetInitialLifecycleState();
Expand Down Expand Up @@ -163,6 +164,16 @@ void main() {
await sendAppExitRequest();
expect(exitRequested, isTrue);
});

test('AppLifecycleListener dispatches memory events', () async {
await expectLater(
await memoryEvents(
() => AppLifecycleListener(binding: WidgetsBinding.instance).dispose(),
AppLifecycleListener,
),
areCreateAndDispose,
);
});
}

class TestAppLifecycleListener extends AppLifecycleListener {
Expand Down

0 comments on commit 2369897

Please sign in to comment.