Flutter ScrollView Observer
Language: English | 中文 | Article
This is a library of widget that can be used to listen for child widgets those are being displayed in the scroll view.
Support
x
ListView
x
SliverList
x
GridView
x
SliverGrid
Installing
Add scrollview_observer
to your pubspec.yaml file:
dependencies:
scrollview_observer: latest_version
Import scrollview_observer
in files that it will be used:
import 'package:scrollview_observer/scrollview_observer.dart';
Getting Started
Take
ListView
as an example
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;
}
...
},
...
);
}
Create ListViewObserver
child
: CreateListView
as a child ofListViewObserver
sliverListContexts
: In this callback, we need to return allBuildContext
of the ListView those needs to be observedonObserve
: 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 index 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);