Flutter-HiveError:盒子已经打开



我想将用户输入写入一个框中以存储它。

我收到错误The box "user_api" is already open and of type Box<String>.

我只在main()函数中打开它,然后在_API_Page_State中关闭它

我很困惑我是怎么一直遇到这个问题的。有人能帮忙吗?谢谢

(在文本输入栏中输入任何内容。(

我的代码:

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'dart:io';
import 'package:fluttertoast/fluttertoast.dart';

Future<void> main() async {
// HIVE SETUP---------------------------------------------
WidgetsFlutterBinding.ensureInitialized();
Directory directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
await Hive.openBox<String>('user_api'); // Initially Opens Box on App Start
await Hive.initFlutter();
// HIVE SETUP---------------------------------------------                      *LATER: Set up Encrypted Box for the API Key. Set Up Unencrypted Box for other information.*
runApp(API_Page_());
}

class API_Page_ extends StatefulWidget {
const API_Page_({Key? key}) : super(key: key);
@override
_API_Page_State createState() => _API_Page_State();}
class _API_Page_State extends State<API_Page_> {
@override
void dispose() {
Hive.box('user_api').close();
super.dispose();
}
final TextEditingController _apiKeyController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Indietools Login'), backgroundColor: Color(0xFF7E57C2),),
body: Center(child: Column(children: <Widget>[
TextField(
decoration: InputDecoration(
label: Text('API Key'),              
),
controller: _apiKeyController,
),
RaisedButton(
onPressed: () {
Text('Store in Box');
final api_key_input = _apiKeyController.text;
var box = Hive.box('user_api');
box.put('API: ', api_key_input);
},
),
RaisedButton(onPressed: () {
Text('Retrieve API in Box');
var box = Hive.box('user_api');
String data = box.get('API');
Fluttertoast.showToast(
msg: data,
toastLength: Toast.LENGTH_LONG,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
})
],
)
),
);}}

我也有同样的问题,Ray Zion提出的解决方案非常适合我。该解决方案与Jake B.在上面评论的相同。

如果使用泛型等待配置单元.openBox<字符串>('user_api'(打开配置单元框,则需要稍后使用泛型配置单元.box<字符串>('user_api'(

您可以参考配置单元规范:https://docs.hivedb.dev/#/basics/boxes?id=type-参数boxltegt

调用openBox:时

。。。为Hive.box((提供相同的类型参数很重要。不能用不同的类型参数多次打开同一个框。

我发现我必须在var box = Hive.box<String>('user_api');中插入<String>

所以修复是:var box = Hive.box<String>('user_api');

相关内容

  • 没有找到相关文章

最新更新