dbx 0.1.0 copy "dbx: ^0.1.0" to clipboard
dbx: ^0.1.0 copied to clipboard

A Data Storage Solution, created with simplicity in mind. It is a simple, lightweight, and fast database solution for Flutter apps.

example/lib/main.dart

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/material.dart';
import 'package:dbx/dbx.dart';
import 'package:path_provider/path_provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Initialize with key seed for consistent demo data across runs
  await DBX.init(
    DBXEncryptionConfig(keySeed: 'demo-key-seed'),
  );
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  final TextEditingController _searchController = TextEditingController();
  List<String> _searchResults = [];
  String _syncStatus = '';

  @override
  void initState() {
    super.initState();
    _loadInitialData();
  }

  Future<void> _loadInitialData() async {
    // Add some demo data for indexing
    DBX.setString('user_name', 'john_doe');
    DBX.setString('user_email', 'john@example.com');
    DBX.setString('app_version', '1.0.0');
    DBX.setString('app_theme', 'dark');
    DBX.setString('notification_enabled', 'true');
  }

  @override
  Widget build(BuildContext context) {
    final files = DBX.getBytesList('files');
    final profilePic = DBX.getBytes('profilePicture');
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('DBX Complete Demo'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Basic Operations
              _buildSection('Basic Typed Operations', [
                if (profilePic != null && profilePic.isNotEmpty)
                  Image.memory(Uint8List.fromList(profilePic), height: 100),
                Text("Message: ${DBX.getString('message') ?? 'No data'}"),
                Text("Username: ${DBX.getString('username') ?? 'No Data'}"),
                Text("Age: ${DBX.getInt('age')}"),
                Text("Height: ${DBX.getDouble('height')}"),
                Text("IsAdmin: ${DBX.getBool('isAdmin')}"),
                Text("Tags: ${DBX.getStringList('tags')?.join(', ') ?? 'None'}"),
                Text("Scores: ${DBX.getIntList('scores')?.join(', ') ?? 'None'}"),
                if (files != null)
                  Wrap(
                    children: files.map((file) => Image.memory(Uint8List.fromList(file), width: 80, height: 80)).toList(),
                  ),
              ]),

              // Generic Operations
              _buildSection('Generic Operations', [
                ElevatedButton(
                  onPressed: () {
                    DBX.set('generic_string', 'Hello Generic!');
                    DBX.set('generic_int', 42);
                    DBX.set('generic_list', [1, 2, 3]);
                    setState(() {});
                  },
                  child: Text('Set Generic Data'),
                ),
                Text("Generic String: ${DBX.get('generic_string')}"),
                Text("Generic Int: ${DBX.get('generic_int')}"),
                Text("Generic List: ${DBX.get('generic_list')}"),
              ]),

              // JSON Objects
              _buildSection('JSON Objects (Custom Dart Objects)', [
                ElevatedButton(
                  onPressed: () {
                    DBX.setJson('user_object', {
                      'name': 'Alice',
                      'age': 28,
                      'preferences': {'theme': 'dark', 'notifications': true},
                      'tags': ['developer', 'flutter']
                    });
                    setState(() {});
                  },
                  child: Text('Store JSON Object'),
                ),
                Text("User Object: ${DBX.getJson('user_object')}"),
              ]),

              // Batch Operations
              _buildSection('Batch Operations', [
                ElevatedButton(
                  onPressed: () {
                    DBX.setStringBulk({'batch1': 'value1', 'batch2': 'value2'});
                    setState(() {});
                  },
                  child: Text('Set Batch Strings'),
                ),
                Text("Batch Data: ${DBX.getStringBulk(['batch1', 'batch2'])}"),
              ]),

              // Indexing & Search
              _buildSection('Indexing & Search', [
                TextField(
                  controller: _searchController,
                  decoration: InputDecoration(labelText: 'Search prefix'),
                ),
                ElevatedButton(
                  onPressed: () {
                    _searchResults = DBX.getKeysStartingWith(_searchController.text);
                    setState(() {});
                  },
                  child: Text('Search'),
                ),
                Text('All Keys: ${DBX.getAllKeys().join(', ')}'),
                Text('Sorted Keys: ${DBX.getAllKeysSorted().join(', ')}'),
                Text('Search Results: ${_searchResults.join(', ')}'),
                Text('Key Count: ${DBX.keyCount}'),
              ]),

              // Sync Operations
              _buildSection('Synchronization', [
                ElevatedButton(
                  onPressed: _exportData,
                  child: Text('Export Data'),
                ),
                ElevatedButton(
                  onPressed: _importData,
                  child: Text('Import Data'),
                ),
                Text('Sync Status: $_syncStatus'),
              ]),

              // Utilities
              _buildSection('Utilities', [
                FutureBuilder<int>(
                  future: DBX.fileSize,
                  builder: (context, snapshot) => Text('File Size: ${snapshot.data ?? 0} bytes'),
                ),
                ElevatedButton(
                  onPressed: () {
                    DBX.removeAll();
                    setState(() {});
                  },
                  child: Text('Clear All Data'),
                ),
              ]),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton.extended(
          onPressed: writeData,
          icon: Icon(Icons.add),
          label: Text("Load Sample Data"),
        ),
      ),
    );
  }

  Widget _buildSection(String title, List<Widget> children) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 20),
        Text(title, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
        SizedBox(height: 10),
        ...children,
        Divider(),
      ],
    );
  }

  Future<void> writeData() async {
    DBX.setString('message', 'Give DBX A Try!! 🎸🀘');
    DBX.setString('username', 'john_doe');
    DBX.setInt('age', 30);
    DBX.setDouble('height', 5.9);
    DBX.setBool('isAdmin', true);
    DBX.setBytes('profilePicture',
        (await rootBundle.load('assets/profile.jpeg')).buffer.asUint8List());
    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', [
      (await rootBundle.load('assets/profile.jpeg')).buffer.asUint8List(),
      (await rootBundle.load('assets/logo.jpeg')).buffer.asUint8List(),
      (await rootBundle.load('assets/file1.jpeg')).buffer.asUint8List(),
      (await rootBundle.load('assets/file2.jpeg')).buffer.asUint8List(),
    ]);
    setState(() {});
  }

  Future<void> _exportData() async {
    try {
      final data = await DBX.exportData();
      final dir = await getApplicationDocumentsDirectory();
      final file = File('${dir.path}/dbx_backup.dbx');
      await file.writeAsBytes(data);
      setState(() => _syncStatus = 'Exported to ${file.path}');
    } catch (e) {
      setState(() => _syncStatus = 'Export failed: $e');
    }
  }

  Future<void> _importData() async {
    try {
      final dir = await getApplicationDocumentsDirectory();
      final file = File('${dir.path}/dbx_backup.dbx');
      if (await file.exists()) {
        final data = await file.readAsBytes();
        await DBX.importData(data);
        setState(() {
          _syncStatus = 'Imported successfully';
        });
      } else {
        setState(() => _syncStatus = 'Backup file not found');
      }
    } catch (e) {
      setState(() => _syncStatus = 'Import failed: $e');
    }
  }
}
5
likes
160
points
133
downloads

Documentation

API reference

Publisher

verified publisherkumpali.com

Weekly Downloads

A Data Storage Solution, created with simplicity in mind. It is a simple, lightweight, and fast database solution for Flutter apps.

Homepage
Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

archive, async, crypto, encrypt, fixnum, flutter, flutter_secure_storage, path_provider, protobuf

More

Packages that depend on dbx