如何使用PageController的当前值更新子窗口小部件(加载指示器)?

时间:2019-02-24 12:42:15

标签: dart flutter loading

仅当LinearProgressIndicator(或PageController)的当前值与其在PageView中的索引相同时,我才想对Row进行动画处理。

如您在屏幕快照中所见,我有一个PageView,其中有LinearProgressIndicator行。 PageView由自己的PageController控制,并且在AnimationController到达结尾时切换页面。

iPhone screenshot with the current outcome

我希望获得类似于this idea的效果,即,仅应为当前页面的LoadingIndicator设置动画。

代码

在下面,您可以找到顶部窗口小部件的代码,即PageView,底部一行LoadingIndicator s。

import 'package:flutter/material.dart';

class PageViewWithLoadingIndicators extends StatefulWidget {
  final List<String> imageUrls;
  final List<Widget> images;
  final Duration totalDuration;
  final Duration transitionDuration;
  final Curve animationCurve;

  const PageViewWithLoadingIndicators(
      {Key key,
      this.imageUrls,
      this.images,
      this.totalDuration = const Duration(seconds: 10),
      this.transitionDuration = const Duration(milliseconds: 700),
      this.animationCurve = Curves.easeInOut})
      : super(key: key);

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

class PageViewWithLoadingIndicatorsState extends State<PageViewWithLoadingIndicators>
    with SingleTickerProviderStateMixin {
  Animation<double> loadingBarAnimation;
  AnimationController controller;
  PageController pageController;
  int count;
  int index;

  @override
  void initState() {
    super.initState();
    assert(widget.imageUrls.isNotEmpty || widget.images.isNotEmpty);

    count = widget.imageUrls.length;
    index = 0;
    controller = AnimationController(duration: widget.totalDuration ~/ count, vsync: this);
    pageController = PageController(initialPage: 0);

    loadingBarAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(controller)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reset();
          setState(() {
            index++;
          });
          if (index == count) {
            setState(() {
              index = 0;
            });
          }
          pageController.animateToPage(index,
              curve: widget.animationCurve, duration: widget.transitionDuration);
        } else if (status == AnimationStatus.dismissed) {
          controller.forward();
        }
      });

    controller.forward();
  }

  @override
  void dispose() {
    controller.dispose();
    pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          child: PageView(
            children: widget.images != null
                ? widget.images
                : widget.imageUrls
                    .map<Widget>((f) => Image.network(
                          f,
                          fit: BoxFit.cover,
                        ))
                    .toList(),
            physics: NeverScrollableScrollPhysics(),
            controller: pageController,
          ),
        ),
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: PageLoader(animation: loadingBarAnimation, count: count),
        )
      ],
    );
  }
}

class PageLoader extends AnimatedWidget {
  final int count;

  PageLoader({Key key, @required this.count, Animation<double> animation})
      : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;

    return Row(
        children: List.generate(
      count,
      (index) => SmallLoadingBar(animation, index),
    ));
  }
}

class SmallLoadingBar extends StatelessWidget {
  final int index;
  final Animation<double> value;

  SmallLoadingBar(this.value, this.index);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
          margin: EdgeInsets.only(top: 10, bottom: 10, left: 5, right: 5),
          height: 5,
          width: double.infinity,
          decoration: BoxDecoration(color: Colors.white24),
          child: LinearProgressIndicator(
              backgroundColor: Colors.transparent,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white70),
              value: value.value)),
    );
  }
}

您可以简单地使用它:

  final List<String> images = [
    'https://i.imgur.com/F8PBP7P.jpg',
    'https://i.imgur.com/DtWaRhg.jpg',
    'https://i.imgur.com/GsRLPXM.jpg',
    'https://i.imgur.com/BMnhHaH.jpg',
    'https://i.imgur.com/qXvgwpw.jpg',
  ];

PageViewWithLoadingIndicators(imageUrls: images)

这里最好的方法是什么?使用InheritedWidget或Stream来检查LoadingIndicator容器内的当前页面索引?

1 个答案:

答案 0 :(得分:1)

  

仅在当前情况下,我想为LinearProgressIndicator设置动画   PageController(或PageView)的值与其在Row中的索引相同。

这对您当前的代码很简单。您要做的就是传递在动画侦听器中更新的索引。首先,您可以稍微简化动画侦听器代码:

setState(() {
    index++;
    if (index == count) {
       index = 0;
    }
});

然后将索引值通过小部件层次结构传递到LinearProgressIndicator,在其中您将使用它:

// in PageViewWithLoadingIndicatorsState's build() method
child: PageLoader(animation: loadingBarAnimation, count: count, current: index),

然后在SmallLoadingBar中,您可以使用传递的值仅对当前的加载指示器进行动画处理:

class SmallLoadingBar extends StatelessWidget {
  final int index;
  final Animation<double> value;
  final int current;

  SmallLoadingBar(this.value, this.index, this.current);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
          margin: EdgeInsets.only(top: 10, bottom: 10, left: 5, right: 5),
          height: 5,
          width: double.infinity,
          decoration: BoxDecoration(color: Colors.white24),
          child: LinearProgressIndicator(
              backgroundColor: Colors.transparent,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white70),
              value: _calculateState(index, current))),
    );
  }

  double _calculateState(int index, int current) {
    // this is the page at which we are so it needs to be animated
    if (index == current) {
      return value.value;
    } else if (index < current) {
      // this is behind the current indicator so was already animated
      return 1;
    } else {
      // this is after the current indicator so it wasn't yet animated
      return 0;
    }
  }
}

当然,要真正完成这项工作,您需要将传递给指示器的动画与实际图像加载时间联系起来。如何执行此操作取决于您计划如何处理图像的加载。