Dart命令行应用程序:计算文本中的行数



你好,我刚开始学习飞镖和长笛,我遇到了一个问题。我有一个文本(实际上它是一个新Flutter项目的main.dart文件中的默认代码(,我需要计算这个文本/代码中的行数,并通过dart命令行输出。我还需要为它定义一个类CodeLineCounter。问题是我根本不明白如何做到这一点,也找不到任何关于这个主题的信息。有人能解释一下或示范一下怎么做吗?

我试着用这个定义,但它错了。

class CodeLineCounter {
void display(){
var text = """
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
""";
Map<String, int> number = Map();
var numberOfLines = text.readAsLinesSync().length;
number["Lines in main.dart"] = numberOfLines;
print(number);
}
}
void main(){
CodeLineCounter lines_counter=CodeLineCounter();
lines_counter.display();
}

readAsLinesSync用于File对象,这些对象是对文件系统上文件的引用。在您的示例中,您的String已经加载(因为它在应用程序中(,所以您不能调用readAsLinesSync

相反,您可以使用LineSplitter,它是dart:convert:的一部分

var numberOfLines = LineSplitter().convert(text).length;

所以你的代码应该是:

import 'dart:convert';
class CodeLineCounter {
void display(){
var text = """
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
""";
Map<String, int> number = Map();
var numberOfLines = LineSplitter().convert(text).length;
number["Lines in main.dart"] = numberOfLines;
print(number);
}
}
void main(){
CodeLineCounter lines_counter=CodeLineCounter();
lines_counter.display();
}

最新更新