How to snap scroll effect in flutter?

2,508

You can use PageView.

enter image description here

Here is the sample code. It has the paging animation. It also has attached listener to the PageController, which is useful to get current state.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _controller = PageController(viewportFraction: 0.6);
  var _color = "";

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.page < 0.5) {
        setState(() {
          _color = "yellow";
        });
      }
      if (_controller.page >= 0.5 && _controller.page < 1.5) {
        setState(() {
          _color = "red";
        });
      }
      if (_controller.page >= 1.5 && _controller.page < 2) {
        setState(() {
          _color = "blue";
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        SizedBox(
          height: 200,
        ),
        Text(
          _color,
          style: TextStyle(fontSize: 40),
        ),
        SizedBox(
          height: 100,
          child: PageView(
            controller: _controller, 
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: SizedBox(
                  child: Container(
                    color: Colors.amber,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: SizedBox(
                  width: 200,
                  child: Container(
                    color: Colors.red,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: SizedBox(
                  width: 200,
                  child: Container(
                    color: Colors.lightBlue,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ));
  }
}
Share:
2,508
rahul  Kushwaha
Author by

rahul Kushwaha

Updated on December 16, 2022

Comments

  • rahul  Kushwaha
    rahul Kushwaha over 1 year

    With the normal scroll effect, you are free to scroll how much ever you want, but I want to have a scrollable list but only scroll full widget or 1/4 of the widget.

    something like this:- enter image description here

    How to get a scrolling effect?