I am using flutter
on android studio(flutter plugin)
and is there anyway i can get the line number of print
statement or debugPrint
statements?
currently it prints as :
flutter: sarmad@
flutter: sarm
flutter: null
It should work for both IOS and android.
I wrote a simple class that gives the current file, line number and column line from the StackTrace.
Heres the code:
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);
}
}
This class takes in a StackTrace object and reads its string and parse it.
How to use it:
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}");
}
The variable programInfo now has the line number, column number and even the file name of the current program's execution.
You can print to the console the following:
print(StackTrace.current.toString());
And you will see how the string looks and be able to understand how i parse the string in order to get the information.
The simple benefit of this is that you dont have to install any library. I made this because i was doing a project just using Dart and i didnt want to add/install any third party library into my simple project. And you will end up with an object having all of the information by just calling the constructor.
NOTE: This code by no means is the most optimize code, but it works :D. I would like to see some better implementations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With