rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

How to snap scroll effect in flutter?

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?

Upvotes: 4

Views: 4753

Answers (1)

easeccy
easeccy

Reputation: 5086

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,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ));
  }
}

Upvotes: 3

Related Questions