简体   繁体   English

检查 Firebase uID 然后路由

[英]Checking for Firebase uID then routing

So my main.dart looking like this, I just want to check if the user already loggedIn or not.所以我的 main.dart 看起来像这样,我只想检查用户是否已经登录。 If true then route him directly to Homescreen and passing the UID else to the SignIn screen.如果为真,则将他直接路由到主屏幕并将 UID 传递到登录屏幕。

But somehow im getting a black screen without any error.但不知何故,我得到一个没有任何错误的黑屏。 Why?为什么? the debug print statements are working...调试打印语句正在工作...

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

//User logged in?
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;

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

  @override
  Widget build(BuildContext context) {
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user == null) {
        print('User is currently signed out!');
        MaterialPageRoute(builder: (context) => const SignIn());
      } else {
        String myUid = user.uid;
        MaterialPageRoute(builder: (context) => HomeScreen(userId: myUid));
        print('User is signed in!');
      }
    });
    return const SizedBox.shrink(); //<-----here
  }
}

Well my Code looking now like this:好吧,我的代码现在看起来像这样:

    Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

//User logged in?
final FirebaseAuth auth = FirebaseAuth.instance;

//The stream for auth changee
Future<User?> data() async {
  return FirebaseAuth.instance.currentUser;
}

final User? user = auth.currentUser;

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
        stream: FirebaseAuth.instance
            .authStateChanges(), //FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Text('Something went wrong');
          }
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }

          if (snapshot.connectionState == ConnectionState.active) {
            if (user == null) {
              print('User is currently signed out!');
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const SignIn()));
            } else {
              String myUid = user!.uid;
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => HomeScreen(
                            userId: myUid,
                          )));
            }
          }
          return const CircularProgressIndicator();
        });
  }
}

Navigator operation requested with a context that does not include a Navigator.使用不包含 Navigator 的上下文请求的 Navigator 操作。 The relevant error-causing widget was StreamBuilder<User?>相关的导致错误的小部件是 StreamBuilder<User?>

You can't just insert a stream listener in the build method like that.您不能像这样在build方法中插入 stream 侦听器。 The easiest way to do this, is to use a StreamBuilder which handles the stream for you.最简单的方法是使用StreamBuilder为您处理 stream。 Similar to the example in the documentation on listening for Firestore updates that'd be something like:类似于文档中关于监听 Firestore 更新的示例,类似于:

StreamBuilder<User?>(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (BuildContext context, AsyncSnapshot<User?> snapshot) {
    if (snapshot.hasError) {
      return const Text('Something went wrong');
    }

    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Text("Loading");
    }

    if (user == null) {
      print('User is currently signed out!');
      return MaterialPageRoute(builder: (context) => const SignIn());
    } else {
      String myUid = user.uid;
      return MaterialPageRoute(builder: (context) => HomeScreen(userId: myUid));
    }
  },

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

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