init
This commit is contained in:
commit
2379b4476f
141 files changed
+6087
No files matched your search
@@ -0,0 +1,176 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
|
||||
import 'app_localizations_zh.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// Callers can lookup localized strings with an instance of AppLocalizations
|
||||
/// returned by `AppLocalizations.of(context)`.
|
||||
///
|
||||
/// Applications need to include `AppLocalizations.delegate()` in their app's
|
||||
/// `localizationDelegates` list, and the locales they support in the app's
|
||||
/// `supportedLocales` list. For example:
|
||||
///
|
||||
/// ```dart
|
||||
/// import 'l10n/app_localizations.dart';
|
||||
///
|
||||
/// return MaterialApp(
|
||||
/// localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
/// supportedLocales: AppLocalizations.supportedLocales,
|
||||
/// home: MyApplicationHome(),
|
||||
/// );
|
||||
/// ```
|
||||
///
|
||||
/// ## Update pubspec.yaml
|
||||
///
|
||||
/// Please make sure to update your pubspec.yaml to include the following
|
||||
/// packages:
|
||||
///
|
||||
/// ```yaml
|
||||
/// dependencies:
|
||||
/// # Internationalization support.
|
||||
/// flutter_localizations:
|
||||
/// sdk: flutter
|
||||
/// intl: any # Use the pinned version from flutter_localizations
|
||||
///
|
||||
/// # Rest of dependencies
|
||||
/// ```
|
||||
///
|
||||
/// ## iOS Applications
|
||||
///
|
||||
/// iOS applications define key application metadata, including supported
|
||||
/// locales, in an Info.plist file that is built into the application bundle.
|
||||
/// To configure the locales supported by your app, you’ll need to edit this
|
||||
/// file.
|
||||
///
|
||||
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
|
||||
/// Then, in the Project Navigator, open the Info.plist file under the Runner
|
||||
/// project’s Runner folder.
|
||||
///
|
||||
/// Next, select the Information Property List item, select Add Item from the
|
||||
/// Editor menu, then select Localizations from the pop-up menu.
|
||||
///
|
||||
/// Select and expand the newly-created Localizations item then, for each
|
||||
/// locale your application supports, add a new item and select the locale
|
||||
/// you wish to add from the pop-up menu in the Value field. This list should
|
||||
/// be consistent with the languages listed in the AppLocalizations.supportedLocales
|
||||
/// property.
|
||||
abstract class AppLocalizations {
|
||||
AppLocalizations(String locale)
|
||||
: localeName = intl.Intl.canonicalizedLocale(locale.toString());
|
||||
|
||||
final String localeName;
|
||||
|
||||
static AppLocalizations? of(BuildContext context) {
|
||||
return Localizations.of<AppLocalizations>(context, AppLocalizations);
|
||||
}
|
||||
|
||||
static const LocalizationsDelegate<AppLocalizations> delegate =
|
||||
_AppLocalizationsDelegate();
|
||||
|
||||
/// A list of this localizations delegate along with the default localizations
|
||||
/// delegates.
|
||||
///
|
||||
/// Returns a list of localizations delegates containing this delegate along with
|
||||
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
|
||||
/// and GlobalWidgetsLocalizations.delegate.
|
||||
///
|
||||
/// Additional delegates can be added by appending to this list in
|
||||
/// MaterialApp. This list does not have to be used at all if a custom list
|
||||
/// of delegates is preferred or required.
|
||||
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates =
|
||||
<LocalizationsDelegate<dynamic>>[
|
||||
delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
];
|
||||
|
||||
/// A list of this localizations delegate's supported locales.
|
||||
static const List<Locale> supportedLocales = <Locale>[Locale('zh')];
|
||||
|
||||
/// No description provided for @run.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'运行'**
|
||||
String get run;
|
||||
|
||||
/// No description provided for @settings.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'设置'**
|
||||
String get settings;
|
||||
|
||||
/// No description provided for @fileDirectory.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'文件目录'**
|
||||
String get fileDirectory;
|
||||
|
||||
/// No description provided for @undo.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'撤销'**
|
||||
String get undo;
|
||||
|
||||
/// No description provided for @redo.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'重做'**
|
||||
String get redo;
|
||||
|
||||
/// No description provided for @save.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'保存'**
|
||||
String get save;
|
||||
|
||||
/// No description provided for @openFileDirectory.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'打开文件目录'**
|
||||
String get openFileDirectory;
|
||||
|
||||
/// No description provided for @viewFileDirectoryHistory.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'查看文件目录历史'**
|
||||
String get viewFileDirectoryHistory;
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate
|
||||
extends LocalizationsDelegate<AppLocalizations> {
|
||||
const _AppLocalizationsDelegate();
|
||||
|
||||
@override
|
||||
Future<AppLocalizations> load(Locale locale) {
|
||||
return SynchronousFuture<AppLocalizations>(lookupAppLocalizations(locale));
|
||||
}
|
||||
|
||||
@override
|
||||
bool isSupported(Locale locale) =>
|
||||
<String>['zh'].contains(locale.languageCode);
|
||||
|
||||
@override
|
||||
bool shouldReload(_AppLocalizationsDelegate old) => false;
|
||||
}
|
||||
|
||||
AppLocalizations lookupAppLocalizations(Locale locale) {
|
||||
// Lookup logic when only language code is specified.
|
||||
switch (locale.languageCode) {
|
||||
case 'zh':
|
||||
return AppLocalizationsZh();
|
||||
}
|
||||
|
||||
throw FlutterError(
|
||||
'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely '
|
||||
'an issue with the localizations generation tool. Please file an issue '
|
||||
'on GitHub with a reproducible sample app and the gen-l10n configuration '
|
||||
'that was used.',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// ignore: unused_import
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
import 'app_localizations.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// The translations for Chinese (`zh`).
|
||||
class AppLocalizationsZh extends AppLocalizations {
|
||||
AppLocalizationsZh([String locale = 'zh']) : super(locale);
|
||||
|
||||
@override
|
||||
String get run => '运行';
|
||||
|
||||
@override
|
||||
String get settings => '设置';
|
||||
|
||||
@override
|
||||
String get fileDirectory => '文件目录';
|
||||
|
||||
@override
|
||||
String get undo => '撤销';
|
||||
|
||||
@override
|
||||
String get redo => '重做';
|
||||
|
||||
@override
|
||||
String get save => '保存';
|
||||
|
||||
@override
|
||||
String get openFileDirectory => '打开文件目录';
|
||||
|
||||
@override
|
||||
String get viewFileDirectoryHistory => '查看文件目录历史';
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"@@locale": "zh",
|
||||
"run": "运行",
|
||||
"settings": "设置",
|
||||
"fileDirectory": "文件目录",
|
||||
"undo": "撤销",
|
||||
"redo": "重做",
|
||||
"save": "保存",
|
||||
"openFileDirectory": "打开文件目录",
|
||||
"viewFileDirectoryHistory": "查看文件目录历史"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/views/main_view.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
title: 'Flutter Demo',
|
||||
theme: ThemeData(
|
||||
useMaterial3: true,
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
|
||||
),
|
||||
home: const MainView(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class FileDirectoryHistory {
|
||||
final String? rootPath;
|
||||
final String? lastOpenedFilePath;
|
||||
final List<String> openDirectoryPaths;
|
||||
|
||||
const FileDirectoryHistory({
|
||||
required this.rootPath,
|
||||
required this.lastOpenedFilePath,
|
||||
this.openDirectoryPaths = const [],
|
||||
});
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
'rootPath': rootPath,
|
||||
'lastOpenedFilePath': lastOpenedFilePath,
|
||||
'openDirectoryPaths': openDirectoryPaths,
|
||||
};
|
||||
|
||||
factory FileDirectoryHistory.fromMap(Map<String, dynamic> map) {
|
||||
return FileDirectoryHistory(
|
||||
rootPath: map['rootPath'] as String?,
|
||||
lastOpenedFilePath: map['lastOpenedFilePath'] as String?,
|
||||
openDirectoryPaths: (map['openDirectoryPaths'] as List<dynamic>?)
|
||||
?.map((e) => e.toString())
|
||||
.toList() ??
|
||||
const [],
|
||||
);
|
||||
}
|
||||
|
||||
String toJson() => jsonEncode(toMap());
|
||||
factory FileDirectoryHistory.fromJson(String source) {
|
||||
try {
|
||||
final decoded = jsonDecode(source);
|
||||
if (decoded is Map) {
|
||||
return FileDirectoryHistory.fromMap(Map<String, dynamic>.from(decoded));
|
||||
}
|
||||
} catch (_) {}
|
||||
return const FileDirectoryHistory(rootPath: null, lastOpenedFilePath: null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
class FileItem {
|
||||
final String path;
|
||||
final String name;
|
||||
final bool isDirectory;
|
||||
final List<FileItem> children;
|
||||
final int depth;
|
||||
bool isOpen;
|
||||
|
||||
FileItem({
|
||||
required this.path,
|
||||
required this.name,
|
||||
this.isDirectory = false,
|
||||
this.children = const [],
|
||||
this.depth = 0,
|
||||
this.isOpen = false
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:code_editor/models/file_directory_history.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class FileDirectoryHistoryService {
|
||||
static final FileDirectoryHistoryService instance = FileDirectoryHistoryService._();
|
||||
FileDirectoryHistoryService._();
|
||||
|
||||
static const String _keyHistory = 'file_directory_history';
|
||||
static const int _maxHistoryCount = 15;
|
||||
|
||||
//记录
|
||||
Future<void> recordHistory({
|
||||
required String rootPath,
|
||||
String? lastOpenedFilePath,
|
||||
List<String>? openDirectoryPaths,
|
||||
}) async {
|
||||
final cleanPath = rootPath.trim();
|
||||
if(cleanPath.isEmpty) return;
|
||||
|
||||
List<FileDirectoryHistory> history = await getFullHistory();
|
||||
|
||||
final existingIndex = history.indexWhere((item) => item.rootPath == cleanPath);
|
||||
String? resolvedFile = lastOpenedFilePath;
|
||||
List<String>? resolvedOpenDirs = openDirectoryPaths;
|
||||
|
||||
if(existingIndex != -1) {
|
||||
resolvedFile ??= history[existingIndex].lastOpenedFilePath;
|
||||
resolvedOpenDirs ??= history[existingIndex].openDirectoryPaths;
|
||||
history.removeAt(existingIndex);
|
||||
}
|
||||
|
||||
history.insert(
|
||||
0,
|
||||
FileDirectoryHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: resolvedFile,
|
||||
openDirectoryPaths: resolvedOpenDirs ?? const [],
|
||||
),
|
||||
);
|
||||
|
||||
if(history.length > _maxHistoryCount) {
|
||||
history.removeRange(_maxHistoryCount, history.length);
|
||||
}
|
||||
|
||||
await _saveHistoryList(history);
|
||||
}
|
||||
|
||||
//获取完整历史
|
||||
Future<List<FileDirectoryHistory>> getFullHistory() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final rawList = prefs.getStringList(_keyHistory) ?? [];
|
||||
return rawList.map((jsonStr) => FileDirectoryHistory.fromJson(jsonStr)).toList();
|
||||
}
|
||||
|
||||
//获取最近历史
|
||||
Future<FileDirectoryHistory?> getLastHistory() async {
|
||||
final history = await getFullHistory();
|
||||
return history.isNotEmpty ? history.first : null;
|
||||
}
|
||||
|
||||
//删除指定的历史
|
||||
Future<void> removeHistory(String path) async {
|
||||
List<FileDirectoryHistory> history = await getFullHistory();
|
||||
history.removeWhere((item) => item.rootPath == path);
|
||||
await _saveHistoryList(history);
|
||||
}
|
||||
|
||||
//清空历史
|
||||
Future<void> clearHistory() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyHistory);
|
||||
}
|
||||
|
||||
Future<void> _saveHistoryList(List<FileDirectoryHistory> list) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final jsonList = list.map((item) => item.toJson()).toList();
|
||||
await prefs.setStringList(_keyHistory, jsonList);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:path/path.dart' as p;
|
||||
import '../models/file_item.dart';
|
||||
|
||||
class FileService {
|
||||
static final FileService instance = FileService._();
|
||||
FileService._();
|
||||
|
||||
//构建文件目录树
|
||||
Future<List<FileItem>> buildTree(
|
||||
String dirPath, {
|
||||
int depth = 0,
|
||||
List<String> openDirectoryPaths = const [],
|
||||
}) async {
|
||||
final rootDir = Directory(dirPath);
|
||||
if(!await rootDir.exists()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
List<FileItem> items = [];
|
||||
|
||||
try {
|
||||
final List<FileSystemEntity> entities = await rootDir.list().toList();
|
||||
for(var entity in entities) {
|
||||
final fileName = p.basename(entity.path);
|
||||
if(fileName.startsWith('.')) continue;
|
||||
|
||||
if(entity is Directory) {
|
||||
final isDirOpen = openDirectoryPaths.contains(entity.path);
|
||||
final children = await buildTree(
|
||||
entity.path,
|
||||
depth: depth + 1,
|
||||
openDirectoryPaths: openDirectoryPaths,
|
||||
);
|
||||
items.add(FileItem(
|
||||
name: fileName,
|
||||
path: entity.path,
|
||||
isDirectory: true,
|
||||
children: children,
|
||||
depth: depth,
|
||||
isOpen: isDirOpen,
|
||||
));
|
||||
}else if(entity is File) {
|
||||
items.add(FileItem(
|
||||
name: fileName,
|
||||
path: entity.path,
|
||||
isDirectory: false,
|
||||
depth: depth,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
items.sort((a, b) {
|
||||
if(a.isDirectory && !b.isDirectory) return -1;
|
||||
if(!a.isDirectory && b.isDirectory) return 1;
|
||||
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
||||
});
|
||||
}catch(e) {
|
||||
print('扫描目录出错: $e');
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
//阅读文件内容
|
||||
Future<String> readFileContent(String path) async {
|
||||
final file = File(path);
|
||||
|
||||
if(!await file.exists()) {
|
||||
throw FileSystemException('文件不存在或已被移除', path);
|
||||
}
|
||||
|
||||
try {
|
||||
return await file.readAsString(
|
||||
encoding: const Utf8Codec(allowMalformed: true),
|
||||
);
|
||||
}catch (e) {
|
||||
throw FileSystemException('读取文件失败: $e', path);
|
||||
}
|
||||
}
|
||||
|
||||
// 写入保存文件
|
||||
Future<void> saveFile(String path, String content) async {
|
||||
final file = File(path);
|
||||
await file.writeAsString(content, encoding: utf8, flush: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/file_directory_history.dart';
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/services/file_directory_history_service.dart';
|
||||
import 'package:code_editor/services/file_service.dart';
|
||||
import 'package:code_editor/widgets/code_editor_widget.dart';
|
||||
import 'package:code_editor/widgets/file_tree_widget.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
class MainView extends StatefulWidget {
|
||||
const MainView({super.key});
|
||||
|
||||
@override
|
||||
State<MainView> createState() => _MainViewState();
|
||||
}
|
||||
|
||||
class _MainViewState extends State<MainView> {
|
||||
List<FileItem> _items = [];
|
||||
FileDirectoryHistory _history = const FileDirectoryHistory(rootPath: null, lastOpenedFilePath: "未命名");
|
||||
bool _isLoading = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadFileItems();
|
||||
}
|
||||
|
||||
Future<void> _loadFileItems() async {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
FileDirectoryHistory? lastHistory = await FileDirectoryHistoryService.instance.getLastHistory();
|
||||
if(lastHistory == null) {
|
||||
if(mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}else {
|
||||
final path = lastHistory.rootPath;
|
||||
List<FileItem> items = (path != null && path.trim().isNotEmpty)
|
||||
? await FileService.instance.buildTree(
|
||||
path,
|
||||
openDirectoryPaths: lastHistory.openDirectoryPaths,
|
||||
)
|
||||
: [];
|
||||
if(mounted) {
|
||||
setState(() {
|
||||
_items = items;
|
||||
_history = lastHistory;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if(mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
|
||||
if(_isLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
final fileName = _history.lastOpenedFilePath;
|
||||
final rootPath = _history.rootPath;
|
||||
|
||||
return Scaffold(
|
||||
//顶部导航栏
|
||||
appBar: AppBar(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
foregroundColor: theme.colorScheme.onPrimaryContainer,
|
||||
title: Text(fileName != null ? p.basename(fileName) : ''),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.undo),
|
||||
tooltip: l10n.undo,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.redo),
|
||||
tooltip: l10n.redo,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.save_outlined),
|
||||
tooltip: l10n.save,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
tooltip: l10n.run,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: l10n.settings,
|
||||
onPressed: () {},
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
//侧边栏
|
||||
drawer: Drawer(
|
||||
child: ListView(
|
||||
padding: EdgeInsets.zero,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(children: [
|
||||
Text(l10n.fileDirectory, style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold
|
||||
)),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.folder_open),
|
||||
tooltip: l10n.openFileDirectory,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: l10n.viewFileDirectoryHistory,
|
||||
onPressed: () {},
|
||||
),
|
||||
]),
|
||||
Text(rootPath ?? '')
|
||||
],
|
||||
),
|
||||
),
|
||||
FileTreeWidget(rootFileItem: _items.isEmpty ? null : _items[0])
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
body: CodeEditorWidget(filePath: _history.lastOpenedFilePath, rootPath: _history.rootPath)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:code_editor/services/file_service.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_code_editor/flutter_code_editor.dart';
|
||||
import 'package:flutter_highlight/themes/atom-one-dark.dart';
|
||||
import 'package:highlight/languages/dart.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
class CodeEditorWidget extends StatefulWidget {
|
||||
final String? rootPath;
|
||||
final String? filePath;
|
||||
|
||||
const CodeEditorWidget({
|
||||
super.key,
|
||||
required this.rootPath,
|
||||
required this.filePath
|
||||
});
|
||||
|
||||
@override
|
||||
State<CodeEditorWidget> createState() => _CodeEditorWidgetState();
|
||||
}
|
||||
|
||||
class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
final CodeController _controller = CodeController();
|
||||
bool _isLoading = false;
|
||||
int _currentLoadVersion = 0;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadFileContent();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant CodeEditorWidget oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.filePath != widget.filePath || oldWidget.rootPath != widget.rootPath) {
|
||||
_loadFileContent();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if(_isLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return CodeTheme(
|
||||
data: CodeThemeData(styles: atomOneDarkTheme),
|
||||
child: CodeField(
|
||||
controller: _controller,
|
||||
gutterStyle: const GutterStyle(
|
||||
showLineNumbers: true,
|
||||
showFoldingHandles: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadFileContent() async {
|
||||
String? fullFilePath;
|
||||
final filePath = widget.filePath;
|
||||
final rootPath = widget.rootPath;
|
||||
|
||||
if (filePath != null && filePath.isNotEmpty) {
|
||||
if (rootPath != null && rootPath.isNotEmpty && !p.isAbsolute(filePath)) {
|
||||
fullFilePath = p.join(rootPath, filePath);
|
||||
} else {
|
||||
fullFilePath = filePath;
|
||||
}
|
||||
}
|
||||
|
||||
if(fullFilePath == null) {
|
||||
_controller.text = '';
|
||||
if(mounted) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = null;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final int requestVersion = ++_currentLoadVersion;
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final content = await FileService.instance.readFileContent(fullFilePath);
|
||||
if(!mounted || requestVersion != _currentLoadVersion) {
|
||||
return;
|
||||
}
|
||||
_controller.language = _resolveLanguage(fullFilePath);
|
||||
_controller.text = content;
|
||||
|
||||
}catch(e) {
|
||||
if(!mounted || requestVersion != _currentLoadVersion) return;
|
||||
setState(() {
|
||||
_errorMessage = '读取文件失败: $e';
|
||||
});
|
||||
}finally {
|
||||
if(mounted && requestVersion == _currentLoadVersion) {
|
||||
setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dynamic _resolveLanguage(String path) {
|
||||
if(path.endsWith('.dart')) return dart;
|
||||
if(path.endsWith('.json')) return json;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class FileItemWidget extends StatefulWidget {
|
||||
final FileItem fileItem;
|
||||
|
||||
const FileItemWidget({
|
||||
super.key,
|
||||
required this.fileItem
|
||||
});
|
||||
|
||||
@override
|
||||
State<FileItemWidget> createState() => _FileItemWidget();
|
||||
}
|
||||
|
||||
class _FileItemWidget extends State<FileItemWidget> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _buildFileItem(context, widget.fileItem);
|
||||
}
|
||||
|
||||
Widget _buildFileItem(BuildContext context, FileItem item) {
|
||||
final indent = EdgeInsets.only(left: item.depth * 16.0 + 8.0, right: 8.0);
|
||||
if(item.isDirectory) {
|
||||
if(item.isOpen) {
|
||||
return GestureDetector(
|
||||
onLongPressStart: (details) {
|
||||
_showContextMenu(context, item, details.globalPosition);
|
||||
},
|
||||
child: ExpansionTile(
|
||||
initiallyExpanded: item.isOpen,
|
||||
onExpansionChanged: (bool expanded) {
|
||||
item.isOpen = expanded;
|
||||
},
|
||||
tilePadding: indent,
|
||||
leading: const Icon(Icons.folder_outlined, color: Colors.amber, size: 20),
|
||||
title: Text(
|
||||
item.name,
|
||||
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
|
||||
),
|
||||
dense: true,
|
||||
children: item.children.map((child) => _buildFileItem(context, child)).toList()
|
||||
)
|
||||
);
|
||||
}else {
|
||||
return GestureDetector(
|
||||
onLongPressStart: (details) {
|
||||
_showContextMenu(context, item, details.globalPosition);
|
||||
},
|
||||
child: ListTile(
|
||||
contentPadding: indent,
|
||||
leading: Icon(Icons.file_copy),
|
||||
title: Text(
|
||||
item.name,
|
||||
style: const TextStyle(fontSize: 13),
|
||||
),
|
||||
dense: true,
|
||||
onTap: () {
|
||||
_openFile(item);
|
||||
},
|
||||
)
|
||||
);
|
||||
}
|
||||
}else {
|
||||
return GestureDetector(
|
||||
onLongPressStart: (details) {
|
||||
_showContextMenu(context, item, details.globalPosition);
|
||||
},
|
||||
child: ListTile(
|
||||
contentPadding: indent,
|
||||
leading: Icon(Icons.file_copy),
|
||||
title: Text(
|
||||
item.name,
|
||||
style: const TextStyle(fontSize: 13),
|
||||
),
|
||||
dense: true,
|
||||
onTap: () {
|
||||
_openFile(item);
|
||||
},
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//打开文件
|
||||
void _openFile(FileItem item) {
|
||||
|
||||
}
|
||||
|
||||
void _showContextMenu(BuildContext context, FileItem item, Offset tapPosition) async {
|
||||
final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
|
||||
final position = RelativeRect.fromRect(
|
||||
Rect.fromLTWH(tapPosition.dx, tapPosition.dy, 0, 0),
|
||||
Offset.zero & overlay.size,
|
||||
);
|
||||
// 弹出 Material 原生菜单
|
||||
final selectedAction = await showMenu<String>(
|
||||
context: context,
|
||||
position: position,
|
||||
color: const Color(0xFF252526),
|
||||
elevation: 8,
|
||||
items: const [
|
||||
PopupMenuItem(
|
||||
value: 'new_file',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.note_add_outlined, size: 18, color: Colors.blueAccent),
|
||||
SizedBox(width: 8),
|
||||
Text('新建文件'),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'rename',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.edit_outlined, size: 18, color: Colors.orangeAccent),
|
||||
SizedBox(width: 8),
|
||||
Text('重命名'),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuDivider(), // 分割线
|
||||
PopupMenuItem(
|
||||
value: 'delete',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.delete_outline, size: 18, color: Colors.redAccent),
|
||||
SizedBox(width: 8),
|
||||
Text('删除', style: TextStyle(color: Colors.redAccent)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
// 用户点击了某一项后的处理逻辑
|
||||
if(selectedAction != null) {
|
||||
_handleMenuAction(context, selectedAction);
|
||||
}
|
||||
}
|
||||
|
||||
void _handleMenuAction(BuildContext context, String action) {
|
||||
switch (action) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'package:code_editor/widgets/file_item_widget.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/file_item.dart';
|
||||
|
||||
class FileTreeWidget extends StatelessWidget {
|
||||
final FileItem? rootFileItem;
|
||||
|
||||
const FileTreeWidget({
|
||||
super.key,
|
||||
required this.rootFileItem
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final root = rootFileItem;
|
||||
if(root == null) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
"请点击上方按钮打开文件目录",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final children = root.children;
|
||||
if(children.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
"目录为空",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
padding: EdgeInsets.zero,
|
||||
itemCount: children.length,
|
||||
itemBuilder: (context, index) {
|
||||
return FileItemWidget(
|
||||
fileItem: children[index],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user