编辑
你可以Hive
box
在main
Box box;
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
box = await Hive.openBox('box');
runApp(MyApp());
}
编辑
问题是代码执行顺序
要使更新的代码正常工作,您必须getCounter()
输入initHive()
原因:Hive box
没有准备好,因为I / O需要时间并且执行时getCounter()
box
仍然null
如果遇到The method 'get/put' was called on null.
这种情况意味着您box
还没有准备好
您必须再次检查async await
和编码执行顺序
并且您不需要box
每次都打开
代码片段
void initHive() async {
await openBox();
getCounter();
}
您可以在下面复制粘贴运行完整代码
第 1 步:您需await _openBox()
要这样做并且initState()
可以使用函数hiveOperation()
来执行async await
代码片段
void hiveOperation() async{
await _openBox();
updateInt();
}
@override
void initState() {
hiveOperation();
super.initState();
}
第 2 步:https ://pub.dev/packages/hive#usage ,您可以Hive
像使用map
. 没有必要await Futures
。
你不需要await newBox.put('updateInt', updateInt);
只是newBox.put('updateInt', updateInt);
会工作
输出
I/flutter ( 5675): 30
完整代码
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
Box box;
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
box = await Hive.openBox('box');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
int counter1;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void getCounter() {
counter1 = box.get('counter1', defaultValue: 0);
_counter = box.get('counter1', defaultValue: 0);
print(counter1);
print(_counter);
// I am not storing any value initially, hence as it is null I want it
//to return the value 0 but the 'get' method keeps getting called on
//null.
}
@override
void initState() {
//initHive();
getCounter();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}