我在main.dart
文件中MaterialApp()
小部件的home
属性内使用StreamBuilder
,以便在WelcomeScreen(包含登录和注册按钮)和DashboardScreen之间导航,并借助firebase_auth
包提供的authStateChanges()
。但无论何时我登录或注册,它只停留在那个屏幕上,直到我手动热重新加载应用程序。我必须热重新加载应用程序,以便从登录屏幕到仪表板。firebase认证工作正常。我可以在firebase控制台中看到已注册的用户。但是屏幕不会自动改变。此外,在登录码或注册码之后没有Navigator.push()
方法。
main.dart:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:banquet_owner_app/screens/welcome_screen.dart';
import 'package:banquet_owner_app/screens/dashboard.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, userSnapshot) {
if (userSnapshot.hasData) {
return Dashboard();
}
return WelcomeScreen();
},
),
);
}
}
你需要得到流的状态,然后检查它是否有数据
这是如何去做
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, userSnapshot) {
if (userSnapshot.connectionState == ConnectionState.waiting) {
//loading screen
}
if (userSnapshot.connectionState == ConnectionState.done) {
//state is loaded check if snapshot has data
if (userSnapshot.hasData) {
return Dashboard();
}else{
return WelcomeScreen();
}
},