颤抖地单击1个按钮应使其余按钮具有动画效果

时间:2019-01-21 15:39:50

标签: dart flutter

主要代码

ListView.builder(
  itemCount: 5,
  itemBuilder: (context, index) {
    return MyWidget(index + 1);
  },
),

MyWidgetStatefulWidget,它的build()方法是

@override
Widget build(BuildContext context) {
  return FadeTransition(
    opacity: _controller,
    child: RaisedButton(
      child: Text(widget.index.toString()),
      onPressed: () {},
    ),
  );
}

需要做什么:

因此,正如您在此处看到的那样,我有5个名为1 2 3 4 5的按钮,我想要实现的是,当我单击任何一个说3的按钮时,除{{ 1}}。我该怎么办?

屏幕截图:

enter image description here

TL; DR:>轻按按钮3时如何为其他按钮设置动画?

1 个答案:

答案 0 :(得分:1)

不确定这是否是最有效的方法,但是可以使用,对于每个ListItem使用AnimatedWidget

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Example")),
        body: AnimatedListView(),
      ),
    );
  }
}

class AnimatedListView extends StatefulWidget {
  @override
  _AnimatedListViewState createState() => _AnimatedListViewState();
}

class _AnimatedListViewState extends State<AnimatedListView>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _animation;

  int _selected;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.ease,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 5,
      itemBuilder: _buildListItem,
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return AnimatedListItem(
      selected: _selected == index,
      animation: _animation,
      onTap: () {
        setState(() {
          _selected = index;
        });
        _controller.forward();
      },
    );
  }
}

class AnimatedListItem extends AnimatedWidget {
  final Tween<double> _opacityTween = Tween(begin: 1, end: 0);

  final GestureTapCallback onTap;
  final bool selected;

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

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return Opacity(
      opacity: selected ? 1.0 : _opacityTween.evaluate(animation),
      child: ListTile(title: Text("Item"), onTap: onTap),
    );
  }
}