GardenMobile & interfaces

Observing memory pressure in Flutter

An older binding observer and cache-clearing experiment, with its limits distinguished from an OOM diagnosis.

A memory-pressure callback is a signal to reconsider retained resources. It does not identify the cause of an out-of-memory failure by itself.

The original state registered a binding observer and removed it during disposal:

class _HomePageState extends BaseState<HomePage> with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didHaveMemoryPressure() {
    print('didHaveMemoryPressure');
  }

}

The earlier cache experiment

# Libs
  path_provider: any
  flutter_cache_manager: ^1.1.3

# Dart
import 'dart:io';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';

...  
  @override
  void didHaveMemoryPressure() async {
    print('didHaveMemoryPressure');
    try {
      DefaultCacheManager().emptyCache();
      PaintingBinding.instance.imageCache.clear();
      final Directory tempDir = await getTemporaryDirectory();
      final Directory libCacheDir = new Directory("$tempDir/libCachedImageData");
      await libCacheDir.delete();
    } catch (e) {
      print(e);
    }
  }

This second listing mixes dependency notes with Dart and uses older cache-manager APIs. Its temporary-directory interpolation, asynchronous cleanup, and deletion scope need review; deleting a cache directory is not equivalent to finding the objects responsible for memory growth.

Inspect allocation and retention with the Flutter memory tools, then choose cleanup based on actual ownership. The source example was not rerun, and no cache files were deleted for this revision.

← Back to the garden