fluttercandies / flutter_scrollview_observer

A widget for observing data related to the child widgets being displayed in a ScrollView. Maintainer: @LinXunFeng
https://pub.dev/packages/scrollview_observer
MIT License
438 stars 47 forks source link

[Discussions] 使用SliverViewObserver监听CustomScrollView之后,onObserveAll回调数据是空的,求解! #72

Closed leaf369369 closed 8 months ago

leaf369369 commented 9 months ago

Content

最近在学习flutter,在如下的这个小demo里,是一个CustomScrollView里面放了一个SliverList,奇怪的是在onObserveAll里面没有返回数据。并且没有任何报错信息,无从下手呐。望在座的各位大佬不吝赐教一下。

/// 存放下标和所对应的 sliver 的 BuildContext
Map<int, BuildContext> sliverContextMap = {};

SliverViewObserver(
  onObserveAll: (Map<BuildContext, ObserveModel> resultModel) {
    resultModel.forEach((context, model) {
      if (model is ListViewObserveModel) {
        /// 这里监听不到数据,返回的数据为 null
        debugPrint(' Model: ${model.firstChild?.index}');
      }
    });
  },
  controller: controller.observerController,
  sliverContexts: () {
    return sliverContextMap.values.toList();
  },
  child: CustomScrollView(
    controller: controller.scrollController,
    slivers: controller.naviList.asMap().entries.map((value) {
      return SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, itemIndex) {
            if (sliverContextMap[value.key] == null) {
              sliverContextMap[value.key] = context;
            }
            return SizedBox(
              height: 50,
              child: Text("--------->$itemIndex"),
            );
          },
          childCount: controller.naviList[value.key].articles!.length,
        ),
      );
    }).toList(),
  ),
)
LinXunFeng commented 8 months ago

你的 controller.naviList 的数据不是一开始就有的吧,在数据发生变化刷新列表视图时需要调用一次 observerController.reattach();