在打开蜂巢盒时出现问题

时间:2020-09-18 09:49:11

标签: flutter

我正在尝试使用一个Hive框来保存数据,但是我关于事物应该如何打开的思维模型显然是错误的。我的问题最简单的版本是...想象一个页面,用户只是想查看存储的数据。

我有一个有阶段的小部件,该小部件在initSate期间打开“ myBox”。我有一个print box.length语句,可以输出正确的盒子长度。

我有一个ValueListenableBuilder侦听该框,并从框中的数据返回ListViewBuilder。

但这是行不通的,至少在最初还是如此。当我执行热重启并从主页导航到此页面时,ListenerBuilder控制台会正确打印该框的长度,但是构建器看不到它并返回循环进度指示器。

如果我随后热加载(而不是重新启动),则列表视图构建器现在可以看到该框并正确构建列表。

我认为这几乎可以肯定是因为该框没有及时打开以绘制屏幕小部件。但是我的开箱呼叫是async / await,所以我看不到要做什么?

编辑-我在主目录中有Hive初始化,而且我很确定它的写法正确,因为列表是在热重新加载后出现的。

    import 'package:flutter/material.dart';
    import 'package:hive/hive.dart';
    import 'package:hive_flutter/hive_flutter.dart';
    
    
    class HiveLoadingCheck extends StatefulWidget {
      @override
      _HiveLoadingCheckState createState() => _HiveLoadingCheckState();
    }
    
    class _HiveLoadingCheckState extends State<HiveLoadingCheck> {
      Box jumpBox;
    
      @override
      void initState() {
        super.initState();
        _hiveOperation();
      }
    
      @override
      void dispose() {
        Hive.close();
        super.dispose();
      }
    
      void _hiveOperation() async {
        print('openingbox');
        jumpBox = await Hive.openBox('Power');
        if (jumpBox != null) {
          print(jumpBox.length);
        }
        return;
      }
    
      @override
      Widget build(BuildContext context) {
        return jumpBox == null
            ? Center(
                child: CircularProgressIndicator(),
              )
            :
        Container(
                child: ValueListenableBuilder(
                    valueListenable: jumpBox.listenable(),
                    builder: (context, Box box, _) {
                      if (box.values.isEmpty) {
                        return Text('data is empty');
                      } else {
                        return ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            reverse: true,
                            shrinkWrap: true,
                            itemCount: box.values.length,
                            itemBuilder: (context, position) {
                              var sampledata = box.getAt(position);
                              return SizedBox(
                                width: MediaQuery.of(context).size.width * .9,
                                child: Card(
                                  color: Colors.grey[200],
                                  elevation: 10,
                                  child: Text(
                                    '${sampledata.sampleID}' ?? 'None',
                                    style: TextStyle(
                                        fontSize: 16, fontWeight: FontWeight.bold),
                                  ),
                                ),
                              );
                            });
                      }
                    }));
      }
    }

0 个答案:

没有答案