Flutter:在无状态小部件中为行内容设置动画
Flutter: Animating Row contents within a stateless widget
我有一个由一个或两个元素组成的行。根据后者,我想为第一个元素的宽度设置动画,使其完全展开或适应第二个元素。
我在行内使用 AnimatedContainers 来实现此目的,但没有动画。我认为这可能与 Flutter 在根据其父级状态重新渲染后无法将其识别为相同有关,因此我尝试使用 Unique Key。然而,这也没有用。
class TabsBar extends StatelessWidget {
TabsBar({this.currentIndex, this.onIndexChanged, Key key}) : super(key: key);
final int currentIndex;
final Function(int) onIndexChanged;
@override
Widget build(BuildContext context) {
final tabsBloc = BlocProvider.of<TabsBarBloc>(context);
return BlocBuilder<TabsBarBloc, TabsBarBlocState>(
builder: (context, tabsBarState) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: standardSpacing),
child: Row(
children: [
Expanded(
child: AnimatedContainer(
key: key,
height: 60,
duration: Duration(milliseconds: 200),
//....//
),
//HERE: IF INDEX IS == 2, I WANT THE CONTAINER ABOVE TO ANIMATE INTO ITS NEW SIZE WHICH IS LESS WIDE TO ACCOMMODATE FOR THE CONTAINER BELOW
currentIndex == 2
? GestureDetector(
onTap: () {},
behavior: HitTestBehavior.translucent,
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
padding: const EdgeInsets.only(left: standardSpacing),
height: 60,
child: Image.asset(
'${imagesPath}add_piece.png',
),
),
)
: HorizontalSpacing(0),
],
),
),
);
});
我还尝试使用 Layout Builder 明确定义宽度,并使用动画容器作为 Row 的父项。都没有用。
任何人都可以指出我可能缺少的东西吗?
我不完全理解您要更改的 AnimatedContainer 的值是什么,但只为该行的第二个容器设置动画并将其宽度更改为 0 使其从屏幕上消失可能更容易
class Home extends StatefulWidget {
@override
State<Home> createState() => HomeState();
}
class HomeState extends State<Home> {
int currentIndex = 2; //or you could use a boolean type
@override
Widget build(BuildContext context) {
return Column(mainAxisSize: MainAxisSize.min, children: [
MyWidget(
currentIndex: currentIndex,
),
FlatButton(
onPressed: () => setState(() {
currentIndex = currentIndex == 1 ? 2 : 1;
}),
child: Text('Change'))
]);
}
}
class MyWidget extends StatelessWidget {
final int currentIndex;
static const double standardSpacing = 8.0;
MyWidget({this.currentIndex, Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: standardSpacing),
child: Row(
children: [
Expanded(
child: Container( //Normal Container
height: 60,
color: Colors.blue)
),
GestureDetector(
onTap: () {},
behavior: HitTestBehavior.translucent,
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
padding: const EdgeInsets.only(left: standardSpacing),
height: 60,
width: currentIndex == 2 ? 36 : 0, //when currentIndex is not 2, it's size its zero
child: const Icon(Icons.save),
),
)
],
),
),
);
}
}