在打印调试信息时,有时我们需要知道在哪个文件,哪一行,此时用print打印并没有文件名和所在行信息,使用xflog能满足需求。
void xflog(Object message, StackTrace current) {
XFCustomTrace programInfo = XFCustomTrace(current);
print("所在文件: ${programInfo.fileName}, 所在行: ${programInfo.lineNumber}, 打印信息: $message");
}
class XFCustomTrace {
final StackTrace _trace;
String fileName;
int lineNumber;
int columnNumber;
XFCustomTrace(this._trace) {
_parseTrace();
}
void _parseTrace() {
var traceString = this._trace.toString().split("\n")[0];
var indexOfFileName = traceString.indexOf(RegExp(r'[A-Za-z_]+.dart'));
var fileInfo = traceString.substring(indexOfFileName);
var listOfInfos = fileInfo.split(":");
this.fileName = listOfInfos[0];
this.lineNumber = int.parse(listOfInfos[1]);
var columnStr = listOfInfos[2];
columnStr = columnStr.replaceFirst(")", "");
this.columnNumber = int.parse(columnStr);
}
}
使用代码:
xflog("******自定义的打印日志", StackTrace.current);
效果演示:
学习内容来自Flutter从入门到实战