Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter & Dart: How to check/know which class has called a function?

I am trying to know which class has called a specific function. I've been looking through the docs for this, but without success. I already know how to get the name of a class, but that is something different of what I'm looking for. I found already something related for java but for dart I haven't. Maybe I'm missing something.

Let's say for example that I have a print function like so:

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();
  }
}

The output should be something like:

you called the function at: B

Please let me know if there are ways to achieve this. The idea behind is to then use this with a logger, for instance the logging package. Thank you in advance.

like image 593
Iván Yoed Avatar asked Jul 07 '26 03:07

Iván Yoed


1 Answers

You can use StackTrace.current to obtain a stack trace at any time, which is the object that's printed when an exception occurs. This contains the line numbers of the chain of invocations leading up to the call, which should provide the information you need.

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

class B {
  A a = A();

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

If you are doing this for debugging purposes, you can also set a breakpoint in printSomethingAndTellWhereYouDidIt to check where it was called from.

like image 156
hacker1024 Avatar answered Jul 09 '26 16:07

hacker1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!