Skip to content

GitLqr/flutter_scrollview_observer

 
 

Repository files navigation

Flutter ScrollView Observer

This is a Widget designed for 'ListView' and 'SliverListView' to listen for which parts are being displayed.

Installing

Add scrollview_observer to your pubspec.yaml file:

dependencies:
  scrollview_observer: ^0.0.1

Import scrollview_observer in files that it will be used:

import 'package:scrollview_observer/scrollview_observer.dart';

Getting Started

BuildContext? _sliverListViewContext;

Create a ListView and record BuildContext in its builder callback

ListView _buildListView() {
  return ListView.separated(
    itemBuilder: (ctx, index) {
      if (_sliverListViewContext != ctx) {
        _sliverListViewContext = ctx;
      }
      return _buildListItemView(index);
    },
    separatorBuilder: (ctx, index) {
      return _buildSeparatorView();
    },
    itemCount: 50,
  );
}

Create ListViewObserver

  • child: Create ListView as a child of ListViewObserver
  • sliverListContexts: In this callback, we need to return all BuildContext of the ListView those needs to be observed
  • onObserve: This callback can listen for information about the child widgets those are currently being displayed
ListViewObserver(
  child: _buildListView(),
  sliverListContexts: () {
    return [if (_sliverListViewContext != null) _sliverListViewContext!];
  },
  onObserve: (resultMap) {
    final model = resultMap[_sliverListViewContext];
    if (model == null) return;

    // Prints the first child widget that is currently being displayed
    print('firstChild.index -- ${model.firstChild.index}');

    // Prints the index of all child widgets those are currently being displayed
    print('displaying -- ${model.displayingChildIndexList}');
  },
)

By default, ListView relevant data will only be observed when rolling. If needed, you can use ListViewOnceObserveNotification triggered an observation manually.

ListViewOnceObserveNotification().dispatch(_sliverListViewContext);

Example

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Dart 43.5%
  • C++ 30.4%
  • CMake 14.3%
  • HTML 7.1%
  • Ruby 2.4%
  • C 1.3%
  • Other 1.0%