【问题标题】:Initialize hive in flutter initState method在flutter initState方法中初始化hive
【发布时间】:2020-07-29 04:27:57
【问题描述】:

我不想调用一些异步函数来获取文档目录并在main 函数中初始化配置单元数据库,而是希望尽可能保持抽象。我想在提供者服务中实现Hive.init(..) 并在initState() 方法期间调用该服务。这样我的main 方法不关心甚至不知道我使用的是什么数据库,而不是调用提供者服务。实现应该是这样的。

service.dart

class Service extends ChangeNotifier {
  ....

  Future<void> init() async {
    Directory dir = await getExternalStorageDirectory();
    Hive.init(dir.path);

 ....

view.dart

class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => Service(),
      child: _MyPageContent(),
    );
  }
}

.....

class _MyPageContent extends StatefulWidget {
  @override
  __MyPageContentState createState() => __MyPageContentState();
}

class __MyPageContentState extends State<_MyPageContent> {
  @override
  void initState() {
    super.initState();
    Provider.of<Service>(context, listen: false).init();
  }
  ....
....

但是,这不起作用。我得到的错误

HiveError (HiveError: You need to initialize Hive or provide a path to store the box.)

原因可能是 Service.init() 方法,作为一个异步方法,在 build 方法执行它的任务时在 initState() 内部被调用。那么有什么办法可以解决这个问题吗?

【问题讨论】:

  • 父级使用服务,而您是从子级初始化它?在MyPage中初始化服务

标签: flutter dart hive


【解决方案1】:

为服务提供一个在加载 Hive 时执行的函数


class Service extends ChangeNotifier {
  Future<void> init(Function onDoneInitializing) async {
    Directory dir = await getExternalStorageDirectory();
    Hive.init(dir.path);
    onDoneInitializing();
  }
}

根据你给Service.init的函数设置的状态改变内容

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  bool doneInitializing = false;
  Service _service;

  @override
  void initState() {
    _service = Service();
    _service.init(() {
      setState(() {
        doneInitializing = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return doneInitializing
        ? ChangeNotifierProvider(
      create: (BuildContext context) => _service,
      child: _MyPageContent(),
    )
        : CircularProgressIndicator();
  }
}

【讨论】:

    【解决方案2】:

    我更改了我的 state 课程,它似乎正在工作。

    class __MyPageContentState extends State<_MyPageContent> {
    
      bool _init = false;
    
      @override
      void initState() {
        super.initState();
        Provider.of<Service>(context, listen: false).init()
        .then((_) => setState(() => _init = true));
      }
      
      @override
      Widget build(BuildContext context) {
        if(_init)
          return MyPreciousWidget(...);
        return CircularProgressIndicator();
      }
    ....
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 2019-12-05
      • 1970-01-01
      • 2022-11-16
      • 2022-01-25
      • 1970-01-01
      • 2022-08-04
      • 2018-09-02
      • 2020-12-22
      相关资源
      最近更新 更多