【问题标题】:Flutter & Dart: How to check/know which class has called a function?Flutter & Dart:如何检查/知道哪个类调用了函数?
【发布时间】:2021-04-24 04:48:54
【问题描述】:

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

假设我有一个这样的打印功能:

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。提前谢谢你。

【问题讨论】:

    标签: flutter dart logging


    【解决方案1】:

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

    class A {
      void printSomethingAndTellWhereYouDidIt() {
        print(StackTrace.current);
      }
    }
    
    class B {
      A a = A();
    
      void test() {
        a.printSomethingAndTellWhereYouDidIt();
      }
    }
    

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

    【讨论】:

    • 感谢您的回答!我认为使用 StackTrace 是要走的路。我现在只需要考虑如何维护类的名称。
    • 我接受这个作为答案。更多信息,我建议去stackoverflow.com/q/49966808/13766744
    猜你喜欢
    • 2021-05-19
    • 2011-03-21
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多