我知道這聽起來很簡單,我瀏覽了檔案中給出的示例。然而不知何故,我無法做到正確。
這就是我所擁有的:
void main() async {
await Hive.initFlutter();
//Hive.openBox('workoutBox');
runApp(const MyApp());
}
...
下一個螢屏:
var box;
...
嘗試添加到框中
Future<void> _save() async{
// save doc id somewhere
final Id = doc.id;
//box = await Hive.openBox('workoutBox');
box.put("Id", Id);
}
嘗試在另一個函式中檢索:
var someId = box.get("Id");
當前錯誤:在 null 上呼叫了 get
我的困惑是,在這種情況下,您在哪里/如何宣告、打開和從盒子中取出?
uj5u.com熱心網友回復:
您似乎忘記了初始化 Box 引數并將 openBox 函式回傳的值分配給它。
在 Hive 初始化之后,你應該有這樣的東西:
Box<myValue> boxValue = await Hive.openBox("myKey");
重要提示:檢索方法將取決于您需要做什么,更重要的是,首先取決于您如何保存資料。
假設您像這樣保存了資料:
await boxValue.add(value);
通過添加這樣的資料,分配給該值的鍵將是一個自動遞增的鍵,因此嘗試使用一開始從未分配過的特定鍵檢索它將會失敗。
如果您確實添加了這樣的資料:
await boxValue.put("myKey", value);
那么您將能夠使用預期的密鑰成功獲取它。
uj5u.com熱心網友回復:
您可以執行以下操作:
void main() async {
await Hive.initFlutter();
await Hive.openBox('workoutBox'); //<- make sure you await this
runApp(const MyApp());
}
...
_save() { // <- can be a synchronous function
final box = Hive.box('workoutBox'); //<- get an already opened box, no await necessary here
// save doc id somewhere
final Id = doc.id;
box.put("Id", Id);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/367334.html
上一篇:如何告訴dart不將map轉換為<String,String>型別而讓它成為<String,Object>型別?
