dbx
一種以簡潔為設計宗旨的資料儲存解決方案。這是一種簡單、輕量且快速的資料庫解決方案,適用於Flutter應用程式。
sumitsharansatsangi/dbx open-source repository details.
以下為英文專案原文快照,最新內容請造訪 GitHub。
dbx is a Dart package designed for secure and efficient local storage using Protocol Buffers instead of JSON.
flutter_secure_storage and encrypted with the encrypt library, with customizable encryption options.int, double, bool, String, Uint8List, List<int>, List<double>, List<bool>, List<String>, List<Uint8List>, and Map<String, dynamic> (JSON).Uint8List for bytes, JSON for custom objectsSharedPreference.
SharedPreference. No headache, easy adaption.🚀Add dbx to your pubspec.yaml:
dependencies:
dbx: ^0.1.0
you can install packages from the command line:
with Flutter:
$ flutter pub get
with Dart:
$ dart pub get
with Flutter:
import 'package:dbx/dbx.dart';
// Basic initialization
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await DBX.init();
runApp(MyApp());
}
// Advanced initialization with custom encryption and path
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await DBX.init(
DBXEncryptionConfig(mode: encrypt.AESMode.gcm, keyLength: 32, ivLength: 16),
'/custom/path/to/storage.dbx' // optional custom file path
);
runApp(MyApp());
}
// Sync-enabled initialization (same keySeed across devices)
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await DBX.init(
DBXEncryptionConfig(
mode: encrypt.AESMode.cbc,
keyLength: 32,
ivLength: 16,
keySeed: 'user-specific-shared-secret' // Derive keys from seed
)
);
runApp(MyApp());
}
with dart:
import 'package:dbx/dbx.dart';
// Example usage
void main() async {
await DBX.init();
}
// Store data
DBX.setString('message', 'Give it a try!');
DBX.setString('username', 'john_doe');
DBX.setInt('age', 30);
DBX.setDouble('height', 5.9);
DBX.setBool('isAdmin', true);
DBX.setBytes(
'profilePicture', File('assets/profile.jpeg').readAsBytesSync());
DBX.setStringList('tags', ['dart', 'flutter']);
DBX.setIntList('scores', [100, 95, 85]);
DBX.setDoubleList('strike_rate', [36.6, 37.0, 36.8]);
DBX.setBoolList('attendence', [true, false, true]);
DBX.setBytesList('files', [
File('assets/file1.jpeg').readAsBytesSync(),
File('assets/logo.jpeg').readAsBytesSync(),
File('assets/file2.jpeg').readAsBytesSync()
]);
// Type-agnostic get/set
DBX.set('generic_string', 'Hello Generic!'); // String
DBX.set('generic_int', 42); // int
DBX.set('generic_list', [1, 2, 3]); // List<int>
String? value = DBX.get('generic_string');
int? number = DBX.get('generic_int');
List<int>? list = DBX.get('generic_list');
// Store JSON objects
DBX.setJson('user_profile', {'name': 'John', 'age': 30, 'active': true});
// Retrieve JSON objects
Map<String, dynamic>? profile = DBX.getJson('user_profile');
// Use with custom objects: User.fromJson(profile!)
// Bulk set
DBX.setStringBulk({'key1': 'value1', 'key2': 'value2'});
// Bulk get
Map<String, String?> values = DBX.getStringBulk(['key1', 'key2']);
// Check existence
bool exists = DBX.containsKey('someKey');
// Get all keys
List<String> allKeys = DBX.getAllKeys();
// Get sorted keys
List<String> sortedKeys = DBX.getAllKeysSorted();
// Prefix search
List<String> appKeys = DBX.getKeysStartingWith('app');
DBX provides export/import functionality for data backup and synchronization across devices.
// Create a backup
Uint8List backupData = await DBX.exportData();
// Save to local file or external storage
await File('/path/to/backup.dbx').writeAsBytes(backupData);
// Restore from backup
Uint8List restoredData = await File('/path/to/backup.dbx').readAsBytes();
await DBX.importData(restoredData);
For syncing data between multiple devices:
await DBX.init(DBXEncryptionConfig(keySeed: 'user-unique-id'));
// On source device - export and upload
Uint8List syncData = await DBX.exportData();
await cloudService.uploadSyncData(syncData);
// On target device - download and import
Uint8List downloadedData = await cloudService.downloadSyncData();
await DBX.importData(downloadedData);
class DBXCloudSync {
static Future<void> uploadToCloud() async {
final data = await DBX.exportData();
// Upload to Firebase Storage, AWS S3, etc.
await FirebaseStorage.instance
.ref('user-data/${userId}/dbx-sync')
.putData(data);
}
static Future<void> downloadFromCloud() async {
final data = await FirebaseStorage.instance
.ref('user-data/${userId}/dbx-sync')
.getData();
if (data != null) {
await DBX.importData(data);
}
}
}
// Usage
await DBXCloudSync.uploadToCloud(); // Backup current data
await DBXCloudSync.downloadFromCloud(); // Restore on new device
Use export/import for periodic backups or when switching devices. For real-time sync, combine with cloud storage webhooks.
Note: For cross-device sync, ensure all devices use the same keySeed during initialization to maintain data compatibility.
// Get statistics
int keyCount = DBX.keyCount;
int fileSize = await DBX.fileSize;
// Remove all data
DBX.removeAll();
// Clear and delete file
DBX.clearAll();
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('DBX Example'),
centerTitle: true,
),
body: Center(
child: FutureBuilder(
future: writeData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final files =DBX.getBytesList('files');
return Column(
children: [
Image.memory(Uint8List.fromList(
DBX.getBytes('profilePicture') ?? [])),
Text("Message: ${DBX.getString('message') ?? 'No data'}"),
Text(
"Username: ${DBX.getString('username') ?? 'No Data'}"), // Output: john_doe
Text("Age: ${DBX.getInt('age')}"), // Output: 30
Text(
"Height: ${DBX.getDouble('height')}"), // Output: 5.9
Text(
"IsAdmin: ${DBX.getBool('isAdmin')}"), // Output: true
Text(
"Tags: ${DBX.getStringList('tags') ?? [].join(',')}"), // Output: [dart, flutter]
Text(
"Scores: ${DBX.getIntList('scores') ?? [].join(',')}"), // Output: [100, 95, 85]
Text(
"Strike Rate: ${DBX.getDoubleList('strike_rate')}"), // Output: [36.6, 37.0, 36.8]
Text(
"Attendence: ${DBX.getBoolList('attendence')}"), // Output: [true, false, true]
if (files != null)
Row(
mainAxisSize: MainAxisSize.min,
children: [
for (final file in files)
Image.memory(Uint8List.fromList(file)),
],
),
],
);
} else {
return CircularProgressIndicator();
}
},
),
),
),
);
}
We welcome contributions from the community! If you have any ideas, suggestions, or bug reports, please open an issue or submit a pull request.
If you find this package useful, please consider sponsoring its development to help us continue improving it. You will be mentioned below
This project is licensed under the MIT License - see the LICENSE file for details.
依賴清單 11 項
{"sdk":"flutter"}^5.0.3^6.0.0^2.1.5^2.13.1^4.0.9^1.1.1^10.1.0^3.0.3{"sdk":"flutter"}^6.1.0先依使用情境篩選,再比較專案活躍情況,最後到原始儲存庫確認使用要求。
“A repository is the most basic element of GitHub.”
GitHub Docs — About repositories ↗