Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update specific field of hive object in flutter?

I am using hive as my NoSQL local database in my flutter app.

Following is my Hive Class:

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

So, my requirement is that on every successful login I am supposed to update profile object. But for that, I have to set all of the others also.

How can I just update the profile object only?

Code:

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

I am using hive version 1.2.0.

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

like image 297
Gaurav Kumar Avatar asked Jan 12 '20 12:01

Gaurav Kumar


2 Answers

Just use the putAt() method, like this:

Hive.box('products').putAt(productIndex, _product);

You can get the productIndex by using the index from the listView.Builder like this:

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

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

          onPressed:(){

        Hive.box('products').putAt(i,product);
      }
    ),
  ]
),
}}
like image 141
Hamza Bashir Avatar answered Nov 15 '22 19:11

Hamza Bashir


Try .save() method:

_personBox = Hive.openBox('personBox');
      await _personBox.then((item) {
        if (!item.isEmpty) {
          print('empty');
          var i = item.getAt(0, PersonModel(...,..,..,..,...,..));
          i.profile = Somevalue;
          i.save();
        }
 });
like image 3
Gagan Raghunath Avatar answered Nov 15 '22 21:11

Gagan Raghunath