gpt4 book ai didi

flutter 和 Dart : How to check/know which class has called a function?

转载 作者:行者123 更新时间:2023-12-01 23:25:52 24 4
gpt4 key购买 nike

我想知道哪个类调用了特定函数。我一直在为此查看文档,但没有成功。我已经知道如何get the name of a class ,但这与我正在寻找的不同。我已经找到something related for java但对于 Dart 我没有。也许我遗漏了什么。

例如,假设我有一个像这样的打印函数:

class A {
void printSomethingAndTellWhereYouDidIt() {
// Here I would also include the class where this function is
// being called. For instance:
print('you called the function at: ...');
//This dot-dot-dot is where maybe should go what I'm looking for.
}
}

class B {
A a = A();

void test() {
a.printSomethingAndTellWhereYouDidIt();
}
}

输出应该是这样的:

you called the function at: B

请告诉我是否有办法实现这一目标。背后的想法是将其与记录器一起使用,例如 the logging package .提前谢谢你。

最佳答案

您可以使用 StackTrace.current随时获取堆栈跟踪,这是发生异常时打印的对象。这包含导致调用的调用链的行号,它应该提供您需要的信息。

class A {
void printSomethingAndTellWhereYouDidIt() {
print(StackTrace.current);
}
}

class B {
A a = A();

void test() {
a.printSomethingAndTellWhereYouDidIt();
}
}

如果您这样做是出于调试目的,您还可以在 printSomethingAndTellWhereYouDidIt 中设置一个断点,以检查它是从哪里调用的。

关于 flutter 和 Dart : How to check/know which class has called a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67239413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com