如何将自定义动画作为Flutter进度/加载指示器?

时间:2020-04-01 03:09:24

标签: flutter dart flutter-animation

我正在尝试用自己的动画替换默认的CircularProgressIndicator。我根据此处的How to rotate an image using Flutter AnimationController and Transform?示例创建了一个旋转的小部件,但是当用“ MyIconSpinner”替换CircularProgressIndicator时,由于某种原因,该小部件没有出现。有什么建议吗? 这是MyIconSpinner的内容

import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';

class MyIconSpinner extends StatefulWidget {
  MyIconSpinner({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyIconSpinnerState extends State<MyIconSpinner>
    with TickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(milliseconds: 5000),
      vsync: this,
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _controller.forward();

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RotationTransition(
              turns: Tween(begin: 0.0, end: 1.0).animate(_controller),
              child: Icon(
                Icons.star,
                size: 40,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

我将其放置在这样的小部件中

return Scaffold(
    appBar: AppBar(
      title: Text("Appbar"),
      backgroundColor: Colors.black,
      automaticallyImplyLeading: false,
    ),
    body: Center(
        child: Column(children: <Widget>[
        StreamBuilder(
            stream: doSomething(withSomeData),
            builder: (BuildContext context,
                AsyncSnapshot<List<DocumentSnapshot>> asyncSnapshot) {
             if (!asyncSnapshot.hasData) return MyIconSpinner();

1 个答案:

答案 0 :(得分:2)

我认为您不应该将MyIconSpinner包裹在Scaffold中。您应提供MyIconSpinner颜色参数,并在完成后重复动画。这是MyIconSpinner的编辑版本。

class MyIconSpinner extends StatefulWidget {
  MyIconSpinner({Key key, this.title, this.color = Colors.blue}) : super(key: key);

  final String title;
  final Color color; 

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

class _MyIconSpinnerState extends State<MyIconSpinner>
    with TickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(milliseconds: 5000),
      vsync: this,
    );

    _controller.addListener((){
      if(_controller.isCompleted){
        _controller.repeat();
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _controller.forward();
    return RotationTransition(
      turns: Tween(begin: 0.0, end: 1.0).animate(_controller),
      child: Icon(
        Icons.star,
        size: 40,
        color: widget.color,
      ),
    );
  }
}