繁体   English   中英

Flutter:如何将 GoRouter 与 Bloc 结合使用以从启动画面路由到登录画面

[英]Flutter: How to use GoRouter with Bloc to route from Splash Screen to Login Screen

所以我最近在我的应用程序中切换到 Go 路由器,因为它很容易实现。 但是我无法从初始屏幕移动到登录屏幕。 我的启动画面中有逻辑,我可以在其中检查用户是否登录。 根据用户的身份验证,屏幕会转到登录屏幕或主页。

这是启动画面。

    class SplashScreen extends StatefulWidget {
  static const routeName = "/SplashScreen";

  const SplashScreen({Key? key}) : super(key: key);

  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<AuthenticationBloc, AuthenticationState>(
      listener: (context, state) {
        if (kDebugMode) {
          print('Listener: $state');
        }
        Future.delayed(const Duration(seconds: 3), () {
          if (state.authStatus == AuthStatus.unAuthenticated) {
            GoRouter.of(context).go('/login');

            Navigator.pushNamed(context, SignUpScreen.routeName);
          } else if (state.authStatus == AuthStatus.authenticated) {
            //Navigator.popUntil(context, (route) => route.isFirst);
            Navigator.pushReplacementNamed(context, HomePage.routeName);
          }
        });
      },
      builder: (context, Object? state) {
        if (kDebugMode) {
          print('object: $state');
        }
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  "Welcome to Musajjal",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                const SizedBox(
                  height: 20,
                ),
                Image.asset(
                  'assets/musajjalBlue.png',
                  width: 300,
                  height: 300,
                ),
                const SizedBox(
                  height: 20,
                ),
                const Text(
                  "Hifz ul Quran Records",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                const SizedBox(
                  height: 20,
                ),
                const CircularProgressIndicator(
                  color: Colors.blueGrey,
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

接下来,这个。 是我的 Go 路由器 function

GoRouter _router(AuthenticationBloc bloc) {
return GoRouter(
  routes: <GoRoute>[
    GoRoute(
      path: '/',
      builder: (context, state) => const SplashScreen(),
      routes: <GoRoute>[
        GoRoute(path: 'login', builder: (context, state) => LoginScreen()),
        GoRoute(
            path: 'signUp', builder: (context, state) => SignUpScreen()),
        GoRoute(path: 'homePage', builder: (context, state) => HomePage())
      ],
      redirect: (BuildContext context, GoRouterState state) {
        final isLoggedIn =
            bloc.state.authStatus == AuthStatus.authenticated;
        final isLoggingIn = state.location == '/login';
        print(isLoggedIn);

        if (!isLoggedIn && !isLoggingIn) return '/login';
        if (isLoggedIn && isLoggingIn) return '/homePage';
        return null;
      },
    ),
  ],
);

}

问题是该应用程序卡在启动画面上,并且不会前进到登录屏幕。 请帮忙。

尝试将重定向中的逻辑更改为

if (!isLoggedIn && !isLoggingIn) return '/login';
if (isLoggedIn) return '/homePage';

另外,考虑将登录逻辑作为 OR 而不是 AND --optional

if (!isLoggedIn || !isLoggingIn) return '/login';

试试下面的代码:

main.dart

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
        providers: [
          BlocProvider<AuthenticationBloc>(
            create: (context) => AuthenticationBloc), 👈 Specify the BlocProvider here
          ),
        ],
        child: MaterialApp(
            theme: customTheme(context),
            debugShowCheckedModeBanner: false,
            routerConfig: router,
  }

router.dart

final GoRouter router = GoRouter(routes: [
  GoRoute(
      path: "/",
      builder: (context, state) {
        return BlocBuilder<AuthCubit, AuthState>(
          buildWhen: (oldState, newState) {
            return oldState is AuthInitialState;
           },
          builder: (context, state) {
             if (state is AuthLoading) {
              // return const SplashScreen();           // alternative way
               context.goNamed(SplashScreen.routeName); 👈 Display your splash screen here and you can provide delay while changing state in your bloc
            }
            else if (state is AuthenticationUnauthenticated) {
               context.goNamed(LoginPage.routeName);  
            } else if (state is Authenticated) {
                context.goNamed(HomePage.routeName);           
             } else {
              return const Scaffold();
            }
          },
        );
      }),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM