Some checks failed
Flutter APK Build / Build Flutter APK (pull_request) Has been cancelled
91 lines
2.5 KiB
Dart
91 lines
2.5 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:file_selector/file_selector.dart';
|
|
import 'package:flutter/services.dart';
|
|
|
|
import '../model/bookmark.dart';
|
|
import '../model/collection.dart';
|
|
import '../assets/constants.dart' as constants;
|
|
|
|
class JsonFileService {
|
|
static Future<bool> exportToJson({
|
|
required List<Collection> collections,
|
|
required List<Bookmark> bookmarks,
|
|
}) async {
|
|
try {
|
|
final dir = await selectDirectoryPath();
|
|
if (dir.isEmpty) return false;
|
|
|
|
saveDataToFile(collections, bookmarks, dir);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static Future<({List<Collection> collections, List<Bookmark> bookmarks})>
|
|
importFromJson() async {
|
|
try {
|
|
const typeGroup = XTypeGroup(label: 'json', extensions: <String>['json']);
|
|
final XFile? file = await openFile(
|
|
acceptedTypeGroups: <XTypeGroup>[typeGroup],
|
|
);
|
|
|
|
if (file == null) {
|
|
return (collections: <Collection>[], bookmarks: <Bookmark>[]);
|
|
}
|
|
|
|
final jsonString = await file.readAsString();
|
|
|
|
final data = jsonDecode(jsonString) as Map<String, dynamic>;
|
|
|
|
final collections = (data['collections'] as List<dynamic>? ?? [])
|
|
.map((json) => Collection.fromJson(json as Map<String, dynamic>))
|
|
.toList();
|
|
|
|
final bookmarks = (data['bookmarks'] as List<dynamic>? ?? [])
|
|
.map((json) => Bookmark.fromJson(json as Map<String, dynamic>))
|
|
.toList();
|
|
|
|
return (collections: collections, bookmarks: bookmarks);
|
|
} catch (e) {
|
|
return (collections: <Collection>[], bookmarks: <Bookmark>[]);
|
|
}
|
|
}
|
|
|
|
static Future<bool> saveDataToFile(
|
|
List<Collection> collections,
|
|
List<Bookmark> bookmarks,
|
|
String directory,
|
|
) async {
|
|
try {
|
|
final data = jsonEncode({
|
|
'collections': collections.map((c) => c.toJson()).toList(),
|
|
'bookmarks': bookmarks.map((b) => b.toJson()).toList(),
|
|
}).codeUnits;
|
|
|
|
final file = XFile.fromData(
|
|
Uint8List.fromList(data),
|
|
mimeType: 'application/json',
|
|
name: constants.jsonFileName,
|
|
);
|
|
|
|
file.saveTo('$directory/${constants.jsonFileName}');
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static Future<String> selectDirectoryPath() async {
|
|
if (Platform.isAndroid) {
|
|
return await getDirectoryPath(
|
|
initialDirectory: constants.defaultAndroidExportDirectory,
|
|
) ??
|
|
'';
|
|
}
|
|
return await getDirectoryPath() ?? '';
|
|
}
|
|
}
|