كيفيه حفظ وعرض البيانات في Hive باستخدام algorithm
في عالم تطوير تطبيقات الهاتف باستخدام Flutter، تُعتبر إدارة البيانات واحدة من أهم التحديات التي يواجهها المطورون. في هذا المقال، سنقوم بتحليل كود Flutter يستخدم Hive كقاعدة بيانات محلية، ونشرح كيفية عمل كل جزء منه. سنتعرف على كيفية إضافة البيانات واسترجاعها بطرق فعالة، مع التركيز على تحسين الأداء.
class TestScreen extends StatelessWidget {
const TestScreen({super.key});
@override
Widget build(BuildContext context) {
var controller = TextEditingController();
var controllerAge = TextEditingController();
Future<Box<Person>> _openPersonBox() async {
return await Hive.openBox<Person>('peopleBox');
}
Future<Box<List<int>>> _openKeysBox() async {
return await Hive.openBox<List<int>>('sortedKeysBox');
}
int _findInsertionIndex(List<int> keys, int newAge, Box<Person> box) {
int low = 0;
int high = keys.length;
while (low < high) {
int mid = (low + high) ~/ 2;
int midAge = box.get(keys[mid])!.age;
if (midAge < newAge) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
return Scaffold(
body: Column(
spacing: 10,
children: [
10.verticalSpace,
AppForm(
controller: controller,
hintText: "name",
),
AppForm(
controller: controllerAge,
hintText: "age",
),
MyButton(
text: "Add",
onPressed: () async {
Box<Person> personBox = await _openPersonBox();
Box<List<int>> keysBox = await _openKeysBox();
for (int i = 0; i < 100000; i++) {
int newAge = Random().nextInt(100000);
Person newPerson = Person(controller.text, newAge);
int newKey = await personBox.add(newPerson);
List<int> sortedKeys = keysBox.get('sortedKeys') ?? <int>[];
int index = _findInsertionIndex(sortedKeys, newAge, personBox);
sortedKeys.insert(index, newKey);
await keysBox.put('sortedKeys', sortedKeys);
}
},
),
MyButton(
text: "get Data",
onPressed: () async {
Box<Person> personBox = await _openPersonBox();
Box<List<int>> keysBox = await _openKeysBox();
List<int> sortedKeys = keysBox.get('sortedKeys') ?? <int>[];
sortedKeys.forEach((key) {
Person? person = personBox.get(key);
if (person != null) {
print('Name: ${person.name}, Age: ${person.age}');
}
});
},
),
ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text("Name: ${index}"),
subtitle: Text("Age: ${index}"),
);
},
)
],
),
);
}
}






