简体   繁体   中英

I want anonymous authenticated users to be redirected to another page

I want to redirect anonymous users to "GuestHomePage" instead of "HomePage" when they launch the app. In my app, authenticated users have their own documents in the "users" collection in the firestore. Therefore, I thought it would be possible to transition the user to another "GuestHomePage" if the user did not have the document in the firestore. But it didn't work. Below is my code. I would like to know what improvements you would like to see.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListenableProvider<UserState>(
      create: (_) => UserState(),
      builder: (context, child) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: StreamBuilder<User?>(
            stream: FirebaseAuth.instance.authStateChanges(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const SizedBox();
              }
              if (snapshot.hasData) {
                String uid = FirebaseAuth.instance.currentUser!.uid;
                try {
                  FirebaseFirestore.instance
                      .collection("users")
                      .doc(uid)
                      .get()
                      .then(
                        (doc) {},
                      );
                  return HomePage();
                } catch (e) {
                  return GuestHomePage();
                }
              }
              return const UserLogin();
            },
          ),
          theme: ThemeData(primarySwatch: Colors.teal),
        );
      },
    );
  }
}

class UserState extends ChangeNotifier {
  User? user;

  void setUser(User newUser) {
    user = newUser;
    notifyListeners();
  }
} 

try this one...

if (snapshot.hasData) {
  String uid = FirebaseAuth.instance.currentUser!.uid;
  try {         
     FirebaseFirestore.instance.collection("users").doc(uid).get().then((doc) {
          var data = doc.data();
          if (data != null) {
            return HomePage();
          } else {
            return GuestHomePage();
          }
        },
      );
    } catch (e) {
      return GuestHomePage();
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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