【问题标题】:Flutter - Firebase auth onAuthStateChanged does not show dashboardFlutter - Firebase auth onAuthStateChanged 不显示仪表板
【发布时间】:2021-07-15 18:19:27
【问题描述】:

我是 Flutter 的新手,在实现 Firebase 身份验证时遇到了一些问题。

所以,我有一个 MaterialApp 小部件,并且我已经注册了一些路线。我有一个包装器 StreamBuilder 来侦听 Firebase onAuthStateChanged 事件,每次我有一个新的用户值时,MaterialApp 都会收到这个新值。

我的问题是我想不出将用户导航到登录屏幕(如果没有当前用户)或仪表板(如果当前用户有效)的最佳方式。你能帮我吗?我在网上找到的每个解决方案都没有实现路由,而是都返回一个小部件。有没有办法通过路线来做到这一点?

下面是我的主类代码:

void main() async {
  // Catch all exceptions and print them to log.
  FlutterError.onError = (FlutterErrorDetails details) {
    logger.e("", details.exception, details.stack);
  };

  // Initialize main engines.
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  // Start main app.
  runApp(
    EasyLocalization(
        supportedLocales: [
          Locale('en', 'US'),
          Locale('el', 'GR')
        ],
        path: 'assets/translations',
        fallbackLocale: Locale('en', 'US'),
        useFallbackTranslations: true,
        child: App(),
    ),
  );
}

class App extends StatelessWidget {
  // Future to initialize firebase.
  final Future<FirebaseApp> _initialization = Firebase.initializeApp(
    options: FirebaseOptions(
        apiKey: "*****************",
        authDomain: "*****************",
        projectId: "*****************",
        storageBucket: "*****************",
        messagingSenderId: "*****************",
        appId: "*****************",
        measurementId: "*****************")
  );

  @override
  Widget build(BuildContext context) {

    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          logger.e("Error while retrieving firebase credentials.", snapshot.error);
          return CircularProgressIndicator();
        }

        // Once complete, show your application
        if (snapshot.connectionState == ConnectionState.done) {
          return StreamBuilder<User?>(
            stream: Authentication.onAuthStateChanged,
            builder: (context, snapshot) {
              // Extract user from snapshot.
              final User? user = snapshot.data;

              return StreamProvider<TreatUser?>(
                create: (_) => TreatUser.streamUser(context, user?.uid),
                initialData: null,
                child: MaterialApp(
                  title: "[Dashboard]",
                  theme: Themes.mainTheme(context),
                  darkTheme: Themes.mainThemeDark(context),
                  themeMode: ThemeMode.light,
                  debugShowCheckedModeBanner: true,
                  localizationsDelegates: context.localizationDelegates,
                  supportedLocales: context.supportedLocales,
                  locale: context.locale,
                  routes: {
                    AppRoutes.login: (context) => LoginScreen(),
                    AppRoutes.passReset: (context) => ResetPassScreen(),
                    AppRoutes.dashboard: (context) => DashboardScreen(),
                    AppRoutes.user_profile: (context) => UserProfile(),
                    AppRoutes.items: (context) => ItemsScreen(),
                  },
                  initialRoute: user != null ? AppRoutes.dashboard : AppRoutes.login,
                ),
              );
            },
          );
        }

        logger.d("Firebase not connected yet. Waiting.");

        // Otherwise, show something whilst waiting for initialization to complete
        return CircularProgressIndicator();
      },
    );
  }
}

提前感谢您的帮助和时间!

【问题讨论】:

    标签: flutter firebase-authentication


    【解决方案1】:

    当 Material App 下有多个 Scaffolds 时会发生这种情况(在身份验证过程之前)。所以 authStateChanges 被另一个替换并且没有响应。

    解决方案是在 initialRoute 或 home 参数中使用 FirebaseAuth.currentUser。

    登录后,手动推送仪表板并删除所有以前的屏幕。

    同样,您也可以注销。

    【讨论】:

      猜你喜欢
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 2021-11-08
      • 2020-02-15
      • 2020-10-01
      • 2019-06-25
      相关资源
      最近更新 更多