You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code中按字母顺序排列Dart文件中的类?

在VS Code中对Dart文件内的类按名称排序

方法1:使用专用扩展

  1. 打开VS Code扩展面板(快捷键 Ctrl+Shift+X / Cmd+Shift+X)
  2. 搜索「Sort Dart Classes」并安装
  3. 打开目标Dart文件,右键空白区域,选择「Sort Classes Alphabetically」,文件内的类会自动按名称字母顺序排列。

方法2:自定义脚本实现(进阶)

如果不想依赖扩展,可以写一个简单的Dart脚本完成排序:

  1. 在项目根目录创建排序脚本(比如 sort_classes.dart),内容如下:
import 'dart:io';

void main() {
  // 替换成你的目标文件路径
  final targetFile = File('lib/sample.dart');
  final content = targetFile.readAsStringSync();
  
  // 匹配类定义(简单正则,适用于常规类结构)
  final classPattern = RegExp(r'class (\w+) {[\s\S]+?^}', multiLine: true);
  final classMatches = classPattern.allMatches(content);
  
  // 将类按名称排序
  final sortedClasses = classMatches.map((match) {
    return {
      'name': match.group(1),
      'code': match.group(0),
    };
  }).toList()
    ..sort((a, b) => a['name']!.compareTo(b['name']!));
  
  // 重新生成文件内容
  final newContent = sortedClasses.map((c) => c['code']).join('\n\n');
  targetFile.writeAsStringSync(newContent);
}
  1. 在VS Code中打开终端,运行 dart run sort_classes.dart 即可完成指定文件的类排序。
  2. 可以将该命令配置为VS Code自定义任务,实现一键调用。

内容的提问来源于stack exchange,提问作者sub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 12:41:05