如何在颤动中捕捉滚动效果?

时间:2019-12-25 17:47:40

标签: flutter scroll widget

使用普通滚动效果,您可以自由滚动所需的大小, 但我想有一个可滚动的列表,但只滚动完整的小部件或小部件的1/4。

类似这样的东西: enter image description here

如何获得滚动效果?

1 个答案:

答案 0 :(得分:1)

您可以使用PageView

enter image description here

这是示例代码。它具有分页动画。它还为PageController附加了侦听器,这对于获取当前状态很有用。

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