| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- import 'dart:convert';
- import 'dart:io';
- import 'package:flutter/foundation.dart';
- import 'package:path_provider/path_provider.dart';
- /// 会话存档:Symja 定义 + 命令历史。
- ///
- /// 写入走「临时文件 + 改名」,保证原子性:写到一半被杀不会留下半个坏存档,
- /// 否则下次启动 JSON 解析失败就会丢掉全部变量。
- class SessionStore {
- static const _fileName = 'session.json';
- static const _version = 1;
- Future<File> _file() async {
- final dir = await getApplicationDocumentsDirectory();
- return File('${dir.path}/$_fileName');
- }
- /// 读存档。任何异常都当成「没有存档」返回 null —— 存档问题绝不能挡住启动。
- Future<Map<String, dynamic>?> load() async {
- try {
- final f = await _file();
- if (!f.existsSync()) return null;
- final decoded = jsonDecode(await f.readAsString());
- if (decoded is! Map<String, dynamic>) return null;
- if (decoded['version'] != _version) return null;
- return decoded;
- } catch (e) {
- debugPrint('读取存档失败,按空存档处理: $e');
- return null;
- }
- }
- Future<void> save(Map<String, dynamic> data) async {
- try {
- final f = await _file();
- final tmp = File('${f.path}.tmp');
- await tmp.writeAsString(
- jsonEncode(<String, dynamic>{'version': _version, ...data}),
- flush: true,
- );
- await tmp.rename(f.path);
- } catch (e) {
- debugPrint('写入存档失败: $e');
- }
- }
- }
|