如何在flutter中更新hive对象的特定字段?

Gau*_*mar 5 flutter flutter-hive

我在我的 flutter 应用程序中使用 hive 作为我的 NoSQL 本地数据库。

以下是我的 Hive 课程:

import 'dart:convert';

import 'package:hive/hive.dart';
import 'package:lpa_exam/src/model/listofexams.dart';
import 'package:lpa_exam/src/model/profile.dart';
part 'hiveprofile.g.dart';

@HiveType()
class PersonModel extends HiveObject{
  @HiveField(0)
  String language;

  @HiveField(1)
  String examName;

  @HiveField(2)
  int examId;

  @HiveField(3)
  Profile profile;

  @HiveField(4)
  ListExam listexam;

  @override
  String toString() {
    return jsonEncode({
      'language': language,
      'examName': this.examName,
      'examId': examId,
      'profile': profile,
      'listexam': listexam
    });
  }

  PersonModel(
      this.language, this.examName, this.examId, this.profile, this.listexam);
}
Run Code Online (Sandbox Code Playgroud)

所以,我的要求是在每次成功登录时我都应该更新配置文件对象。但为此,我还必须设置所有其他人。

我怎样才能只更新配置文件对象?

代码:

_personBox = Hive.openBox('personBox');
          await _personBox.then((item) {
            if (!item.isEmpty) {
              print('empty');
              item.putAt(0, PersonModel(...,..,..,..,...,..));
            }
          });
Run Code Online (Sandbox Code Playgroud)

我正在使用配置单元版本1.2.0。

参考:https : //resocoder.com/2019/09/30/hive-flutter-tutorial-lightweight-fast-database/

小智 10

只需使用该putAt()方法,如下所示:

Hive.box('products').putAt(productIndex, _product);
Run Code Online (Sandbox Code Playgroud)

productIndex您可以通过使用索引来获取,listView.Builder 如下所示:

ListView.builder(
  itemBuilder: (cxt, i) {

    return Row(
      children:[
      Text(product[i].name),
        MaterialButton(
          child:Text('edit'),

          onPressed:(){

        Hive.box('products').putAt(i,product);
      }
    ),
  ]
),
}}
Run Code Online (Sandbox Code Playgroud)


小智 3

尝试 .save() 方法:

_personBox = Hive.openBox('personBox');
      await _personBox.then((item) {
        if (!item.isEmpty) {
          print('empty');
          var i = item.getAt(0, PersonModel(...,..,..,..,...,..));
          i.profile = Somevalue;
          i.save();
        }
 });
Run Code Online (Sandbox Code Playgroud)