首页 > 解决方案 > 如果在 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"),
        ),
      ),
    );
  }
}

标签: flutterflutter-animation

解决方案


推荐阅读