[英]How do I manage navigation routes table with Flutter connected to Firebase Firestore
I wonder how to manage screen navigation when your app is connected to Firebase.我想知道当您的应用程序连接到 Firebase 时如何管理屏幕导航。 When my app was offline I used a routes table, but Im not sure how to do now.当我的应用程序离线时,我使用了路由表,但我现在不知道该怎么做。 Could I do as I show with my code below;我可以按照下面的代码所示做吗? use a streambuilder that switches between the AuthScreen when logged out and HomeScreen when logged in, and a routes table to switch with the following screens also when signed in.使用在注销时在 AuthScreen 和登录时在 HomeScreen 之间切换的流构建器,以及在登录时也使用以下屏幕切换的路由表。
I tried this approach but when im signing out from another screen than the HomeScreen the user stays signed in.我尝试了这种方法,但是当我从另一个屏幕而不是 HomeScreen 退出时,用户保持登录状态。
How can I set up my routes so that the user always signs out independent from which screen the user's currently on.如何设置我的路线,以便用户始终独立于用户当前所在的屏幕退出。
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterApp',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (
ctx,
userSnapshot,
) {
if (userSnapshot.hasData) {
return HomeScreen();
}
return AuthScreen();
}),
routes: {
Screen1.routeName: (ctx) => Screen1(),
Screen2.routeName: (ctx) => Screen2(),
Screen3.routeName: (ctx) => Screen3(),
Screen4.routeName: (ctx) => Screen4(),
});
}
}
I don't think you're going about this the right way.我不认为你这样做是正确的。
They are various ways of doing this.他们有各种方法来做到这一点。 Here's mine.这是我的。
Firstly, I think you should define an initial route that checks if the user is signed in.首先,我认为您应该定义一个初始路由来检查用户是否已登录。
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterApp',
theme: ThemeData(
primarySwatch: Colors.orange,
),
initialRoute:
FirebaseAuth.instance.currentUser == null ? "/login" : "/home",
routes: {
"/home": (ctx) => HomeScreen(),
"/login": (ctx) => AuthScreen(),
Screen1.routeName: (ctx) => Screen1(),
Screen2.routeName: (ctx) => Screen2(),
Screen3.routeName: (ctx) => Screen3(),
Screen4.routeName: (ctx) => Screen4(),
});
}
Note: "/home"
& "/login"
could be whatever you want as long as it's a string.注意: "/home"
和"/login"
可以是任何你想要的,只要它是一个字符串。
For logout, you need to replace the current screen with the login page, something like this should do.对于注销,您需要用登录页面替换当前屏幕,应该这样做。
Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.