Home > Net >  How to print a Class's file path?
How to print a Class's file path?

Time:11-29

I want to print the Class's file path so I can located this class very quickly.

It's just like sometimes system do:

enter image description here

I can click this blue link and jump to it's Class.

How can I do in my class?

This method like:

printPath(this.runtimeType);

CodePudding user response:

Edit: It's not answer for your question but it can help you with finding your implementation. Actually, you should use your IDE to locate your classes.

That is stack trace. You can get stack trace with throwing an error. Just put try-catch clause anywhere in the code like that:

try {
  throw Error();
} catch (e, stackTrace) {
  print(stackTrace);
}

You can improve that by writing extension:

extension StackTracer on Object {
  StackTrace get stackTrace {
    try {
      throw Error();
    } catch (e, stackTrace) {
      return stackTrace;
    }
  }
}

And you can get it by importing extenstion and just print it like that:

import 'package:flutter/material.dart';

import 'path_to_your_extension.dart'; // path to your extension

class CrashButton extends StatelessWidget {
  const CrashButton({super.key});

  @override
  Widget build(BuildContext context) {
    print(stackTrace);
    return Text('Widget');
  }
}

But in this case you will get path to your extension as a first path

Stack trace with extension

CodePudding user response:

Add this package:

 stack_trace: ^1.11.0

Example:

import 'dart:async';

void main() {
  _scheduleAsync();
}

void _scheduleAsync() {
  Future.delayed(Duration(seconds: 1)).then((_) => _runAsync());
}

void _runAsync() {
  throw 'oh no!';
}

Unhandled exception:
oh no!
#0      _runAsync (file:///Users/kevmoo/github/stack_trace/example/example.dart:12:3)
#1      _scheduleAsync.<anonymous closure> (file:///Users/kevmoo/github/stack_trace/example/example.dart:8:52)
<asynchronous suspension>
  • Related