Flutter how do scroll controllers work,how do they get executed

Viewed 451

Flutter : i am new to flutter , i wanted to know how do they work behind the scenes(what actually happens when we attach a scroll controller to a scrollable widget.) . i read the docs but its hard for me to understand.

                  controller: ** _controller **,
                  scrollDirection: Axis.vertical,
                  child: Wrap(
                    // direction: Axis.horizontal,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    spacing: 4.0,
                    runSpacing: 4.0,
                    children: *MY WIDGET*,
                  ),```
1 Answers

This is a good question and something I was curious about as well. If you're using ListView, it subclasses another class called BoxScrollView which itself subclasses ScrollView and it's in fact ScrollView that holds onto the ScrollController instance if you look at this code:

  /// {@template flutter.widgets.scroll_view.controller}
  /// An object that can be used to control the position to which this scroll
  /// view is scrolled.
  ///
  /// Must be null if [primary] is true.
  ///
  /// A [ScrollController] serves several purposes. It can be used to control
  /// the initial scroll position (see [ScrollController.initialScrollOffset]).
  /// It can be used to control whether the scroll view should automatically
  /// save and restore its scroll position in the [PageStorage] (see
  /// [ScrollController.keepScrollOffset]). It can be used to read the current
  /// scroll position (see [ScrollController.offset]), or change it (see
  /// [ScrollController.animateTo]).
  /// {@endtemplate}
  final ScrollController? controller;

If you then look in the build() function of ScrollView you'll see this gem:

  @override
  Widget build(BuildContext context) {
    final List<Widget> slivers = buildSlivers(context);
    final AxisDirection axisDirection = getDirection(context);

    final ScrollController? scrollController =
        primary ? PrimaryScrollController.of(context) : controller;
    final Scrollable scrollable = Scrollable(
      dragStartBehavior: dragStartBehavior,
      axisDirection: axisDirection,
      controller: scrollController,

You see the Scrollable instance which takes the controller in as a parameter?

I'm not going to paste more code since it can get quite long but I suggest that you go ahead and look at the source code for Scrollablle and also ScrollView to get a better understanding of how they work.

Related