如果在Flutter中重建父窗口小部件,如何使AnimatedSwitcher动画化?

时间:2019-12-06 10:11:01

标签: flutter flutter-animation

我正在尝试实现可选的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"),
        ),
      ),
    );
  }
}

0 个答案:

没有答案