How to add animated transitions when changing Widget on BLoC pattern?

寵の児 提交于 2019-12-07 08:21:48

问题


so I was following bloc login tutorial, and while I managed to complete it, I'm still fairly new to Flutter & Dart.

There is a portion of the code where, depending on the state, the code returns a different widget, instead of a new Scaffold. Since it's not using routes, the transition between pages looks choppy and akward.

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

I've tried adding a Navigation.push wrapping the returns, like this:

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

But while is not syntactically wrong, that crashes the app. Does anyone know a way to implement this while maintaining the BLoC example? Thanks.


回答1:


You can wrap the pages with 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),
        );
      },
    ),
  ),
);

By default it uses fade transition and animates old and new widgets in reverse order.


To keep old widget in place during animation, pass to AnimatedSwitcher

switchOutCurve: Threshold(0),

To mimic Navigator.push transition in Android, pass it

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

To use system transitions, try something like

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

(the last isn't tested well)



来源:https://stackoverflow.com/questions/55581110/how-to-add-animated-transitions-when-changing-widget-on-bloc-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!