Flutter: Make a “Scroll Back To Top” button

Last updated on March 2, 2022 A Goodman Loading... 5 comments

The Back-To-Top button is helpful when the screen of your application is long and contains a lot of content. It allows the user to quickly scroll back to the top of the page.

In the beginning, the Back-To-Top button is invisible and only shows up when the user scrolls down a distance. This behavior eliminates the redundancy and makes the screen cleaner when the view is at the very top of the page.

A Complete Example

App Preview:

Complete code (with explanations):

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  // this variable determnines whether the back-to-top button is shown or not
  bool _showBackToTopButton = false;

  // scroll controller
  late ScrollController _scrollController;

  @override
  void initState() {
    _scrollController = ScrollController()
      ..addListener(() {
        setState(() {
          if (_scrollController.offset >= 400) {
            _showBackToTopButton = true; // show the back-to-top button
          } else {
            _showBackToTopButton = false; // hide the back-to-top button
          }
        });
      });

    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose(); // dispose the controller
    super.dispose();
  }

  // This function is triggered when the user presses the back-to-top button
  void _scrollToTop() {
    _scrollController.animateTo(0,
        duration: const Duration(seconds: 3), curve: Curves.linear);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: SingleChildScrollView(
        controller: _scrollController,
        child: Column(
          children: [
            // add a bunch of containers to make the screen longer
            Container(
              height: 600,
              color: Colors.amber,
            ),
            Container(
              height: 600,
              color: Colors.blue[100],
            ),
            Container(
              height: 600,
              color: Colors.red[200],
            ),
            Container(
              height: 600,
              color: Colors.orange,
            ),
            Container(
              height: 600,
              color: Colors.yellow,
            ),
            Container(
              height: 1200,
              color: Colors.lightGreen,
            ),
          ],
        ),
      ),
      // This is our back-to-top button
      floatingActionButton: _showBackToTopButton == false
          ? null
          : FloatingActionButton(
              onPressed: _scrollToTop,
              child: const Icon(Icons.arrow_upward),
            ),
    );
  }
}

The above example is quite simple but it has provided you with all the necessary knowledge to deploy a back-to-top button in real production apps.

If you would like to learn more about Flutter, take a look at the following articles:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
5 Comments
Inline Feedbacks
View all comments
undertaker21
undertaker21
1 year ago
SafeArea(
  child: Scaffold(
    body: Builder(
        builder: (context){
          _scrollController = ScrollController()..addListener(() {
            setState(() {
              if (_scrollController.offset >= 400) {
                _showBackToTopButton = true; // show the back-to-top button
              } else {
                _showBackToTopButton = false; // hide the back-to-top button
              }
            });
          });
          return CustomScrollView(
            controller: _scrollController,
            slivers: <Widget>[
              SliverPersistentHeader()...
undertaker21
undertaker21
1 year ago

Before it work with a CustomScrollView i had to wrap the CustomScrollView widget with a Builder() and move the _scrollController initialisation code from the initState() method to Builder() widget body before returning another widget.


Lastmentor
Lastmentor
1 year ago

I’m using this method to prevent “laggy” to scroll up. Plus I’m not using the setState method in initstate. My goal is, when I’m at the bottom and after clicking a button go top.

_scrollController.animateTo(0,
    duration: Duration(milliseconds: 250), curve: Curves.linear);
Ramana
Ramana
1 year ago

I think this is method is laggy, because of setState every single time, are you have any other method to fix this?

Related Articles