flutter - 如果在 Flutter 中重建父小部件,如何使 AnimatedSwitcher 动画?
问题描述
我正在尝试实现一个可选择的ListTile
. 当ListTile
被选中时,它的前导图标会发生变化,并且其背景颜色也会发生变化。我正在尝试使用AnimatedSwitcher在更改图标时为过渡设置动画。它可以工作(只要我不更改列表图块的背景颜色)。
更改背景颜色ListTile
会导致动画不再起作用。我想我知道为什么会这样。当背景颜色ListTile
改变时,整体ListTile
被重建。这AnimatedSwitcher
也导致重建而不是在图标之间转换。有没有办法可以实现我正在尝试做的事情。这是我的完整代码。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool change = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: SomeStatelessWidget(
AnimatedSwitcher(
duration: Duration(seconds: 2),
child: change
? CircleAvatar(
key: UniqueKey(),
child: Icon(Icons.check),
)
: CircleAvatar(
key: UniqueKey(),
child: Text("A"),
),
transitionBuilder: (child, animation) {
return RotationTransition(
turns: animation,
child: child,
);
},
),
change),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.swap_horiz),
onPressed: () {
setState(() {
change = !change;
});
},
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerFloat,
));
}
}
class SomeStatelessWidget extends StatelessWidget {
final Widget child;
final bool changed;
SomeStatelessWidget(this.child, this.changed);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(8.0),
decoration: changed
? BoxDecoration(
color: Theme.of(context).selectedRowColor,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
shape: BoxShape.rectangle)
: null,
child: ListTile(
leading: child,
title: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("This is an example"),
),
),
);
}
}
解决方案
推荐阅读
- hash - 如何在 Redis Hash 上执行搜索?
- http2 - HTTP/2 客户端可以选择通过服务器推送接收哪些资源吗?
- javascript - 带有分类类的 highcharts 地图气泡
- postgresql - 仅使用 appsync api 和数据源作为 posgresql 更新给定的列值
- html - CSS按钮不会改变颜色
- javascript - 删除两个内部``````元素之间的空格
- html - 导航栏在移动视图上的高度翻倍
- list - sortedByDescending 列表 Flutter
- docker - docker:OCI运行时创建失败:json:无法将对象解组为[]字符串类型的Go值:未知
- c# - ASP.NET Core 访问 Inetpub 外部的文件夹