Home > Software design >  how to read index in hive on flutter?
how to read index in hive on flutter?

Time:11-14

hi I try using hive as my database in flutter but i can not read the index of records. as the code below, first I search in box and find If box have specific value or not. after that i want update that recode if funded but I do not know how to read index. curranty I use 0 but I want do it dynamically.
`

var userBox = await Hive.openBox('User');
var filterUser = userBox.values
    .where((User) => User.token == 'CFx8D7662DxV8FH1Gwt4')
    .toList();

if(filterUser.isNotEmpty){
  User user = User(
      filterUser[0].username,
      filterUser[0].password,
      filterUser[0].hint,
      filterUser[0].name,
      filterUser[0].imageAddress,
      '-1',
      null,
      null);
  await userBox.putAt(0, user);
  Get.offNamed(Routs.introScreen1);

`

CodePudding user response:

you can use this example of hive document:

import 'package:hive/hive.dart';

void main() async {
  Hive.registerAdapter(PersonAdapter());
  var persons = await Hive.openBox('persons');

  var person = Person()
    ..name = 'Lisa';

  persons.add(person); // Store this object for the first time

  print('Number of persons: ${persons.length}');
  print("Lisa's first key: ${person.key}");

  person.name = 'Lucas';
  person.save(); // Update object

  person.delete(); // Remove object from Hive
  print('Number of persons: ${persons.length}');

  persons.put('someKey', person);
  print("Lisa's second key: ${person.key}");
}

@HiveType()
class Person extends HiveObject {
  @HiveField(0)
  String name;
}

class PersonAdapter extends TypeAdapter<Person> {
  @override
  final typeId = 0;

  @override
  Person read(BinaryReader reader) {
    return Person()..name = reader.read();
  }

  @override
  void write(BinaryWriter writer, Person obj) {
    writer.write(obj.name);
  }
}
  • Related