debugFindConstructingStackFrame static method

  1. @visibleForTesting
String? debugFindConstructingStackFrame([
  1. StackTrace? stackTrace
])

Finds the first non-constructor frame in the stack trace.

stackTrace defaults to StackTrace.current.

Implementation

@visibleForTesting
static String? debugFindConstructingStackFrame([StackTrace? stackTrace]) {
  String? stackFrame;

  assert(() {
    if (debugAddStackTraceInObserverName) {
      final stackTraceString = (stackTrace ?? StackTrace.current).toString();
      final rawStackFrame = LineSplitter.split(stackTraceString)
          // We are skipping frames representing:
          // 1. The anonymous function in the assert
          // 2. The debugFindConstructingStackFrame method
          // 3. The constructor invoking debugFindConstructingStackFrame
          //
          // The 4th frame is either user source (which is what we want), or
          // an Observer subclass' constructor (which we skip past with the
          // regex)
          .skip(3)
          // Search for the first non-constructor frame
          .firstWhere(
              (frame) => !_constructorStackFramePattern.hasMatch(frame),
              orElse: () => '');

      final stackFrameCore =
          _stackFrameCleanUpPattern.firstMatch(rawStackFrame)?.group(1);
      final cleanedStackFrame = stackFrameCore == null
          ? null
          : 'Observer constructed from: $stackFrameCore';

      stackFrame = cleanedStackFrame;
    }

    return true;
  }());

  return stackFrame;
}