2

I save a List to an index in a Hive Box.

class Person { 
 String name;
 Person(this.name);
}

List<Person> friends = [];
friends.add(Person('Jerry'));

var accountBox = Hive.openBox('account');
accountBox.put('friends',friends);

//Testing as soon as saved to make sure it's storing correctly.
List<Person> friends = accountBox.get('friends');
assert(friends.length == 1);

so all this works as intended. For some crazy reason when I hot restart the app and try to get the list of friends from Hive, it no longer returns a List<Person>. It returns a List<dynamic>

var accountBox = Hive.openBox('account');
List<Person> friends = accountBox.get('friends');

///ERROR
E/flutter (31497): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled
Exception: type 'List<dynamic>' is not a subtype of type 'List<Person>'
E/flutter (31497): <asynchronous suspension>
etc...

What could be causing this? It's so unusual.


How to map array using ObjectMapper?

Here is my model

class ResponseDataType: Mappable {

    var status: Int?
    var message: String?
    var info: [Info]?

    required init?(map: Map) { }

    func mapping(map: Map) {
        status <- map["status"]
        message <- map["message"]
        info <- map["member_info"]
    }
}

Here is my JSON

"status": 200,
    "data": {
        "member_info": [
            {
                "fullname": "werwerwer",
                "type": "werwer",
                "profile_image": "sdfsdfsd.jpg",
                "email": "wfwe@werwegt",
                "contact": ""
            }
        ]
    },
    "message": "Login Success"
}

Im having a hard time mapping the array inside the data. Please tell me what is wrong with my code.

4

3 回答 3

3

Hive 主要是具有文件缓存的内存数据库。当应用程序运行时,它可能会将您放入其中的对象按原样存储在内存中,但将对象作为序列化二进制数据存储在缓存文件中。这意味着只要应用程序处于打开状态,您就会取回您的Person列表,但它不知道如何从缓存文件中获取该数据。结果是 Hive 尽最大努力反序列化数据并将其作为dynamic.

如果您想在应用程序关闭后保持数据完整,您需要告诉 Hive 如何(反)序列化您的类型。为此,请使用 Hive 注释适当地标记您的类。

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

  Person(this.name);
}
于 2020-02-28T20:33:30.417 回答
2

有一种简单的方法可以转换回您的信息。

List<T> myList = box.get('key', defaultValue: <T>[]).cast<T>();

正如您在此示例中看到的那样,当您获取数据时,您只需要告诉类型即可正确分配数据。

于 2020-09-24T05:39:49.200 回答
2

这为我解决了问题

var fooBox = await Hive.openBox<List>("Foo");

var foosList = fooBox.get("foos", defaultValue: []).cast<Foo>();
print(foosList);

这个来自github问题的解决方案

于 2021-01-04T06:45:02.333 回答