【问题标题】:How to Stop the flutter rebuilds from ValueListenableBuilder?如何停止 ValueListenableBuilder 的颤动重建?
【发布时间】:2022-11-28 01:08:33
【问题描述】:

我遇到了从 ValueListenableBuilder 内部不断重建的小部件子树的问题。它应该在更改时运行重建,在这种情况下,它正在监听 Flutter Hive 数据库上的表。
我累的事情:

  1. 我在 main 方法中打开了所有 Hive Box,这样我就可以从应用程序的任何位置访问每个 Box。我厌倦了只有在发生变化时才打开 Hive 框,然后立即关闭这个框。没用

    我认为可能是但不确定的事情:

    1. 将 ChangeNotifierProvider 与 ValueListenableBuilder 混合 - 因为某些子树也使用 changenotifier,但是随着 ValueListenableBuilder 不断重建子树,我传递给提供者的任何更改都会被清除。

      无论如何只能重建变化吗?

        @override
        Widget build(BuildContext context) {
          return ValueListenableBuilder(
              valueListenable:
                  Hive.box<Manifest>(HiveTables.manifestBox).listenable(),
              child: assignmentWidgets,
              builder: (context, Box<Manifest> manifestBox, child) {
                if (manifestBox.isNotEmpty)
                  return child!;
              },
              );
        }
      

【问题讨论】:

    标签: flutter dart flutter-provider flutter-hive


    【解决方案1】:

    Hive 提供对整个 Box 的监听,所以每次 Box 中发生某些事情时,都会调用构建器:

     ValueListenableBuilder<Box>(
      valueListenable: Hive.box('settings').listenable(),
      builder: (context, box, widget) {
        // build widget
      },
    ),
    

    但您也可以指定一个 List&lt;String&gt; 键,您只希望它们可以被 ValueListenableBuilderkeys 属性监听,如下所示:

    ValueListenableBuilder<Box>(
      valueListenable: Hive.box('settings').listenable(keys: ['firstKey', 'secondKey']),
      builder: (context, box, widget) {
        // build widget
      },
    ),
    

    现在除了键第一键secondKey,对它们执行的每个操作都不会更新ValueListenableWidget,但操作第一键第二个键只会更新它。

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 1970-01-01
      • 2020-10-19
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多