debugAssertNoTransientCallbacks method

bool debugAssertNoTransientCallbacks(
  1. 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>.of(
        _transientCallbacks,
      );
      FlutterError.reportError(
        FlutterErrorDetails(
          exception: reason,
          library: 'scheduler library',
          informationCollector:
              () => <DiagnosticsNode>[
                if (count == 1)
                  // TODO(jacobr): I have added an extra line break in this case.
                  ErrorDescription(
                    'There was one transient callback left. '
                    'The stack trace for when it was registered is as follows:',
                  )
                else
                  ErrorDescription(
                    'There were $count transient callbacks left. '
                    'The stack traces for when they were registered are as follows:',
                  ),
                for (final int id in callbacks.keys)
                  DiagnosticsStackTrace(
                    '── callback $id ──',
                    callbacks[id]!.debugStack,
                    showSeparator: false,
                  ),
              ],
        ),
      );
    }
    return true;
  }());
  return true;
}