Created
October 25, 2024 16:59
-
-
Save RockinPaul/604305c58d246ec280aed5fd5cbf4744 to your computer and use it in GitHub Desktop.
Dart function to extract the current method name from the stack trace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Helper function to extract the current method name from the stack trace | |
String getCurrentMethodName() { | |
final frames = StackTrace.current.toString().split('\n'); | |
// The second frame in the stack trace contains the current method | |
final frame = frames.elementAtOrNull(1); | |
if (frame != null) { | |
// Extract the method name from the frame. For example, given this input string: | |
// #1 LoggerAnalyticsClient.trackAppOpen (package:flutter_ship_app/src/monitoring/logger_analytics_client.dart:28:9) | |
// The code will return: LoggerAnalyticsClient.trackAppOpen | |
final tokens = frame | |
.replaceAll('<anonymous closure>', '<anonymous_closure>') | |
.split(' '); | |
final methodName = tokens.elementAtOrNull(tokens.length - 2); | |
if (methodName != null) { | |
// if the class name is included, remove it, otherwise return as is | |
final methodTokens = methodName.split('.'); | |
// ignore_for_file:avoid-unsafe-collection-methods | |
return methodTokens.length >= 2 && | |
methodTokens[1] != '<anonymous_closure>' | |
? (methodTokens.elementAtOrNull(1) ?? '') | |
: methodName; | |
} | |
} | |
return ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment