Flutter:获取print()语句的行号,Android Studio

Sar*_*hah 6 flutter

我正在使用flutter,android studio(flutter plugin)无论如何我可以获得print声明或debugPrint声明的行号?

目前打印为:

flutter: sarmad@
flutter: sarm
flutter: null
Run Code Online (Sandbox Code Playgroud)

它应该适用于IOSandroid.

Mah*_*oos 9

我假设您出于调试目的需要它。

您可以在打印语句中手动放置行号(放置类和/或方法的名称对我来说更好)。

你可以使用:

print(StackTrace.current);
Run Code Online (Sandbox Code Playgroud)

或者这个(几乎相同):

debugPrintStack();
Run Code Online (Sandbox Code Playgroud)

打印堆栈跟踪,其中包括调用打印和行号的类和方法,以及使输出混乱的堆栈跟踪的其余部分。因此,您可以使用debugPrintStack(label: 'sarmad',maxFrames: 2);仅打印当前堆栈跟踪的前 2 行。


Lui*_*v99 6

我编写了一个简单的类,它提供了来自 StackTrace 的当前文件、行号和列行。

代码如下:

class CustomTrace {
  final StackTrace _trace;

  String fileName;
  int lineNumber;
  int columnNumber;

  CustomTrace(this._trace) {
    _parseTrace();
  }

  void _parseTrace() {
    /* The trace comes with multiple lines of strings, we just want the first line, which has the information we need */
    var traceString = this._trace.toString().split("\n")[0];

    /* Search through the string and find the index of the file name by looking for the '.dart' regex */
    var indexOfFileName = traceString.indexOf(RegExp(r'[A-Za-z]+.dart'));

    var fileInfo = traceString.substring(indexOfFileName);

    var listOfInfos = fileInfo.split(":");

    /* Splitting fileInfo by the character ":" separates the file name, the line number and the column counter nicely.
      Example: main.dart:5:12
      To get the file name, we split with ":" and get the first index
      To get the line number, we would have to get the second index
      To get the column number, we would have to get the third index
    */

    this.fileName = listOfInfos[0];
    this.lineNumber = int.parse(listOfInfos[1]);
    var columnStr = listOfInfos[2];
    columnStr = columnStr.replaceFirst(")", "");
    this.columnNumber = int.parse(columnStr);
  }
}
Run Code Online (Sandbox Code Playgroud)

这个类接受一个 StackTrace 对象并读取它的字符串并解析它。

如何使用它:

void main() {
  CustomTrace programInfo = CustomTrace(StackTrace.current);

  print("Source file: ${programInfo.fileName}, current line of code since the instanciation/creation of the custom trace object: ${programInfo.lineNumber}, even the column(yay!): ${programInfo.columnNumber}");
}
Run Code Online (Sandbox Code Playgroud)

变量programInfo现在具有当前程序执行的行号、列号甚至文件名。

您可以将以下内容打印到控制台:

print(StackTrace.current.toString());
Run Code Online (Sandbox Code Playgroud)

您将看到字符串的外观,并能够理解我如何解析字符串以获取信息。

这样做的简单好处是您不必安装任何库。我这样做是因为我正在使用 Dart 做一个项目,我不想在我的简单项目中添加/安装任何第三方库。并且您将通过调用构造函数最终得到一个包含所有信息的对象。

注意:此代码绝不是最优化的代码,但它有效:D。我想看到一些更好的实现