Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter ScrollController position in NestedScrollView

Tags:

flutter

I have a NestedScrollView that houses a SliverAppBar with a TabBarView and the tabs consist of an infinite loading list each. Right now I only have one ScrollController attached to NestedScrollView, and list widgets read the scroll position of this controller.

The infinite loading logic uses controller.position.extentAfter to decide when to fetch data from the API. But with multiple tabs, I get the error

ScrollController attached to multiple scroll views.

I tried reading about controller.positions but couldn't make sense of the 2 line documentation that's available. My question is, is it possible to access scroll positions per page in a TabBarView or should I just use separate ScrollController for each of those and forget about the correct scrolling of slivers?

like image 999
ishaan Avatar asked Jan 31 '26 23:01

ishaan


1 Answers

You can't use the same controller for different scroll views. This is the reason you are getting this error "ScrollController attached to multiple scroll views." However, you can listen to the PrimaryScrollController and update your infinite list to fetch more data from the API. If you look at the code of NestedScrollView you would find the PrimaryScrollController there.

NestedScrollView(
  body: Builder(builder: (BuildContext context) {
    final innerScrollController = PrimaryScrollController.of(context);
    // Use the innerScrollController to listen to the scrolling.
    // This would be your controller for list. You can listen to this controller to know whether the list has reached maxScrollExtent and fetch data from API.
    }),
 );

For reference:

The [body] is built in a context that provides a [PrimaryScrollController] that interacts with the [NestedScrollView]'s scroll controller. Any [ListView] or other [Scrollable]-based widget inside the [body] that is intended to scroll with the [NestedScrollView] should therefore not be given an explicit [ScrollController], instead allowing it to default to the [PrimaryScrollController] provided by the [NestedScrollView].

like image 175
Debasmita Sarkar Avatar answered Feb 03 '26 18:02

Debasmita Sarkar