【问题标题】:How to add animated transitions when changing Widget on BLoC pattern?如何在 BLoC 模式上更改 Widget 时添加动画过渡?
【发布时间】:2019-08-30 01:21:09
【问题描述】:

所以我关注了bloc login tutorial,虽然我设法完成了它,但我对 Flutter 和 Dart 还是很陌生。

有一部分代码根据状态返回不同的小部件,而不是新的 Scaffold。由于它没有使用路由,因此页面之间的过渡看起来很不稳定。

return BlocProvider<AuthenticationBloc>(
  bloc: authenticationBloc,
  child: MaterialApp(
    debugShowCheckedModeBanner: false,
    home: BlocBuilder<AuthenticationEvent, AuthenticationState>(
      bloc: authenticationBloc,
      builder: (BuildContext context, AuthenticationState state) {
        if (state is AuthenticationUninitialized) {
          return SplashPage();
        }
        if (state is AuthenticationAuthenticated) {
          return HomePage();
        }
        if (state is AuthenticationUnauthenticated) {
          return LoginPage(userRepository: userRepository);
        }
        if (state is AuthenticationLoading) {
          return LoadingIndicator();
        }
      },
    ),
  ),
);

我尝试添加一个 Navigation.push 包装返回,如下所示:

if (state is AuthenticationUninitialized) {
  Navigation.push(
    return SplashPage();
  ),
}

虽然在语法上没有错误,但这会使应用程序崩溃。有谁知道在维护 BLoC 示例的同时实现这一点的方法?谢谢。

【问题讨论】:

    标签: flutter flutter-animation bloc


    【解决方案1】:

    你可以用AnimatedSwitcher包裹页面:

    return BlocProvider<AuthenticationBloc>(
      bloc: authenticationBloc,
      child: MaterialApp(
        home: BlocBuilder<AuthenticationEvent, AuthenticationState>(
          bloc: authenticationBloc,
          builder: (BuildContext context, AuthState state) {
            return AnimatedSwitcher(
              duration: Duration(milliseconds: 250),
              child: _buildPage(context, state),
            );
          },
        ),
      ),
    );
    

    默认情况下,它使用淡入淡出过渡并以相反的顺序为新旧小部件设置动画。


    要在动画期间保留旧的小部件,请传递给 AnimatedSwitcher

    switchOutCurve: Threshold(0),
    

    要在 Android 中模仿 Navigator.push 转换,请传递它

    transitionBuilder: (Widget child, Animation<double> animation) {
      return SlideTransition(
        position: Tween<Offset>(
          begin: const Offset(0, 0.25),
          end: Offset.zero,
        ).animate(animation),
        child: child,
      );
    },
    

    要使用系统转换,请尝试类似

    transitionBuilder: (Widget child, Animation<double> animation) {
      final theme = Theme.of(context).pageTransitionsTheme;
      final prev = MaterialPageRoute(builder: (_) => widget);
      return theme.buildTransitions(prev, context, animation, null, child);
    },
    

    (最后一个没测试好)

    【讨论】:

    • 此外,AnimatedSwitcher 的子级必须有一个 Key 来表示更改。如果您不想修改您的子 Widget(它是 StatelessWidget 或有自己的密钥的 StatefulWidget),用 Container 包装它并将 Container 密钥设置为:UniqueKey()。
    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多