How to use ClampingScrollPhysics in Top and BouncingScrollPhysics in Bottom on a Scroll List

Hello Flutterian, Today we are going to see a piece of code which will help you to play with your scroll list in your mobile application. In scroll view, we may sometime use BouncingScrollPhysics or ClampingScrollPhysics, which gives a separate look on list respectively at Top & Bottom Simultaneously.

What if, we wants to use ClampingScrollPhysics in Top and BouncingScrollPhysics in Bottom only in our list. Here I came up with a solution which will provide us as per our desired ScrollPhysics.

 

import 'package:flutter/material.dart';

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

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

class _ScrollDemoState extends State<ScrollDemo> {
  ScrollController scrollController = ScrollController();
  ScrollPhysics _physics = const ClampingScrollPhysics();

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels <= 56) {
        _physics = const ClampingScrollPhysics();
      } else {
        _physics = const BouncingScrollPhysics();
      }
      setState(() {});
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Scroll Physics Demo"),
      ),
      body: ListView.builder(
        controller: scrollController,
        physics: _physics,
        itemCount: 20,
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        itemBuilder: (context, index) {
          return Card(
            elevation: 1,
            child: ListTile(
              leading: CircleAvatar(
                child: Text("$index"),
              ),
              title: Text("#$index Item"),
            ),
          );
        },
      ),
    );
  }
}

 

Now, try it in your next project and explore more by play with it.
Happy Coding, Thanks.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *