Chapters

Hide chapters

Flutter Apprentice

First Edition – Early Access 3 · Flutter 1.22.6 · Dart 2.10.5 · Android Studio 4.1.2

Section III: Navigating Between Screens

Section 3: 3 chapters
Show chapters Hide chapters

Section IV: Networking, Persistence and State

Section 4: 7 chapters
Show chapters Hide chapters

Appendices

Section 6: 2 chapters
Show chapters Hide chapters

A. Appendix A: Chapter 5 Solution 1
Written by Vincent Ngo

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

First you need to make ExploreScreen a StatefulWidget. That is because you need to preserve the state of the scroll controller.

Next add a ScrollController property in _ExploreScreenState:

ScrollController _controller;

Then, add a function called scrollListener(), which is the function callback that will listen to the scroll offsets.

void _scrollListener() {
  // 1
  if (_controller.offset >= _controller.position.maxScrollExtent &&
      !_controller.position.outOfRange) {
    print('i am at the bottom!');
  }
  // 2
  if (_controller.offset <= _controller.position.minScrollExtent &&
      !_controller.position.outOfRange) {
    print('i am at the top!');
  }
}

Here’s how the code works:

  1. Check the scroll offset, and see if the position is greater than or equal to the maxScrollExtent. That means the user has scrolled to the very bottom.
  2. Check if the scroll offset is less than or equal to the minScrollExtend. That means the user has scrolled to the very top.

Within _ExploreScreenState, override the initState() method as shown below:

@override
void initState() {
  // 1
  _controller = ScrollController();
  // 2
  _controller.addListener(_scrollListener);
  super.initState();
}

Here’s how the code works:

  1. You initialize the scroll controller.
  2. You add a listener to the controller. Every time the user scrolls, scrollListener() will get called.

Within the ExploreScreen’s parent ListView, all you have to do is set the scroll controller as shown below:

return ListView(
        controller: _controller,
        ...

That will tell the scroll controller to listen to this particular list view’s scroll events.

Some use cases for when you might need a scroll controller:

  • Detect if you are at a certain offset.
  • Control the scroll movement by animating to a specific index.
  • Check to see if the scroll view has started, stop, or ended.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now