如何在Flutter上读取Hive中索引?

nbnkbykc  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(249)

嗨,我尝试使用hive作为flutter中的数据库,但我无法读取记录的索引。如下面的代码,首先我在框中搜索,并找到是否框有特定的值。之后,我想更新重新编码,如果有资金,但我不知道如何读取索引。curranty我使用0,但我想动态地做。
`

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);

`

cl25kdpy

cl25kdpy1#

您可以使用以下配置单元文档示例:

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);
  }
}

相关问题