主要代码:
ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return MyWidget(index + 1);
},
),
MyWidget
是StatefulWidget
,它的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}}。我该怎么办?
屏幕截图:
TL; DR:>轻按按钮3时如何为其他按钮设置动画?
答案 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),
);
}
}