flutterdart

How to implement the disposable pattern in Dart?


I know the disposable pattern from C#.

However, I wonder a little bit on how it is implemented and used in Dart and Flutter. I saw it being used in Flutter like this:

@override
void dispose() {
    // dispose own stuff here
    super.dispose();
}

Now it's the first time I wanted to implement it myself in a class without a widget base class. In some library, I found a Disposable base class and the dispose() method.

However, the method signature is different

@override
Future<Null> dispose() async {

}

In C#, there is an interface one needs to implement in order to satisfy the disposable pattern. Does such an interface (base class) exist for Dart? Or is it just that everyone implements a dispose method with an arbitrary signature and whoever uses the class must be smart enough to find the method and figure out how to call it?


Solution

  • There is no method that is always called when an object is "disposed". Depending on the state management system you use, this is handled differently. I would (personally) recommend a state management system with Provider and/or Bloc. Here you can use e.g. the method close to release your resources when a Bloc is removed from the widget tree. https://pub.dev/packages/provider
    https://pub.dev/packages/flutter_bloc

    Other state management systems: https://docs.flutter.dev/data-and-backend/state-mgmt/options

    If you just use StatefulWidgets for your state management (not recommended), you use the dispose method to free your resources.

    EDIT: As @RandalSchwartz said, my answer was not fully correct. There is the Finalizer class in Dart that allows you to dispose objects once they become unreachable. However, this is not best practice in Flutter and should not be used as a general pattern.