debugAssertNoTransientCallbacks method

bool debugAssertNoTransientCallbacks (String reason)

Asserts that there are no registered transient callbacks; if there are, prints their locations and throws an exception.

A transient frame callback is one that was registered with scheduleFrameCallback.

This is expected to be called at the end of tests (the flutter_test framework does it automatically in normal cases).

Call this method when you expect there to be no transient callbacks registered, in an assert statement with a message that you want printed when a transient callback is registered:

assert(SchedulerBinding.instance.debugAssertNoTransientCallbacks(
  'A leak of transient callbacks was detected while doing foo.'
));

Does nothing if asserts are disabled. Always returns true.

Implementation

bool debugAssertNoTransientCallbacks(String reason) {
  assert(() {
    if (transientCallbackCount > 0) {
      // We cache the values so that we can produce them later
      // even if the information collector is called after
      // the problem has been resolved.
      final int count = transientCallbackCount;
      final Map<int, _FrameCallbackEntry> callbacks = Map<int, _FrameCallbackEntry>.from(_transientCallbacks);
      FlutterError.reportError(FlutterErrorDetails(
        exception: reason,
        library: 'scheduler library',
        informationCollector: (StringBuffer information) {
          if (count == 1) {
            information.writeln(
              'There was one transient callback left. '
              'The stack trace for when it was registered is as follows:'
            );
          } else {
            information.writeln(
              'There were $count transient callbacks left. '
              'The stack traces for when they were registered are as follows:'
            );
          }
          for (int id in callbacks.keys) {
            final _FrameCallbackEntry entry = callbacks[id];
            information.writeln('── callback $id ──');
            FlutterError.defaultStackFilter(entry.debugStack.toString().trimRight().split('\n')).forEach(information.writeln);
          }
        }
      ));
    }
    return true;
  }());
  return true;
}