为什么在AnimatedBuilder()中嵌套AnimatedSwitcher()不起作用?

3
当我运行以下代码时,在用户登录时,AnimatedBackground()成功地进行了动画,页面从LoginScreen()更改为HomeScreen(),但是在过渡时没有任何动画。
我怀疑这与嵌套动画和不恰当的重建有关,但是使用keys修复后问题仍旧存在。
class AuthenticationWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final User? firebaseuser = context.watch<User?>();
    print("build run with user $firebaseuser");
    return SafeArea(
        child: AnimatedBackground(
      key: Key("salt123value${firebaseuser == null}"),
      animate: firebaseuser == null ? false : true,
      child: AnimatedSwitcher(
          key: Key("animatedswitcher"),
          transitionBuilder: AnimatedSwitcher.defaultTransitionBuilder,
          duration: const Duration(seconds: 4),
          child: firebaseuser == null
              ? LoginScreen(
                  key: Key("login"),
                )
              : HomeScreen(
                  key: Key("home"),
                )),
    ));
  }
}

N.B. AnimatedBackground是一个自定义小部件,返回一个CustomPaint(child:child)或者一个包含在AnimatedBuilder中的CustomPaint。

这可能是因为AnimatedBckground (animate: bool)根据animate的值返回不同深度的小部件树。


请注意:您可以使用firebaseuser!= null而不是firebaseuser == null?false:true - Nabeel Parkar
1个回答

1
最终,将AnimatedSwticher.defaultLayoutBuilder包装在我的动画小部件中起了作用。
class AuthenticationWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final User? firebaseuser = context.watch<User?>();
    return SafeArea(
        child: AnimatedSwitcher(
            layoutBuilder: (currentChild, previousChildren) =>
                AnimatedBackground(
                  key: ValueKey<String>(firebaseuser?.uid.toString() ?? "none"),
                  animate: firebaseuser != null,
                  child: AnimatedSwitcher.defaultLayoutBuilder(
                      currentChild, previousChildren),
                ),
            duration: const Duration(seconds: 1),
            child: firebaseuser == null ? LoginScreen() : HomeScreen()));
  }
}

所以我的动画和AnimatedSwitcher动画都运行了,互不影响。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接