Using Isar Database and Shared Preferences in MessengerX App
In Flutter, both Isar Database and Shared Preferences are powerful tools to manage and store data. This documentation provides a brief guide on how to integrate and use Isar Database for more complex data management and Shared Preferences for lightweight data storage
Prerequisites
1.Flutter development environment set up.
Isar Database
In your pubspec.yaml file, add the isar package:
isar: ^0.14.0
Run flutter pub get to install the dependency.
Initializing Isar
Initialize Isar in your main.dart:
import 'package:isar/isar.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Isar.init();
runApp(MyApp());
}
Defining Models
Define your data models using Isar annotations:
import 'package:isar/isar.dart';
@Collection()
class Person {
int id = 0;
String name = '';
@override
String toString() => 'Person(id: $id, name: $name)';
}
CRUD Operations
Perform CRUD (Create, Read, Update, Delete) operations using Isar:
Learn more on How to use Isar Db in your application
Shared Preferences
Installation
In your pubspec.yaml file, add the shared_preferences package:
shared_preferences: ^2.0.13
Saving Data
import 'package:shared_preferences/shared_preferences.dart';
Future saveData() async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('username', 'john_doe');
prefs.setInt('age', 25);
}
Reading Data
Future readData() async {
final prefs = await SharedPreferences.getInstance();
final username = prefs.getString('username') ?? '';
final age = prefs.getInt('age') ?? 0;
print('Username: $username, Age: $age');
}
Removing Data
Future removeData() async {
final prefs = await SharedPreferences.getInstance();
prefs.remove('username');
prefs.remove('age');
}
Perform CRUD (Create, Read, Update, Delete) operations using Shared Preferences:
Learn more on How to use Shared Preferences in your application