25

所以我一直在关注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 示例的同时实现这一点的方法?谢谢。

4

1 回答 1

27

您可以使用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),

要模仿Navigator.pushAndroid 中的转换,请传递它

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);
},

(最后一个没有测试好)

于 2019-04-10T00:33:25.350 回答