我在我的android应用中使用firebase作为后端服务。如果用户未登录,我试图将用户导航到登录屏幕。我正在检查 main.dart 文件中的身份验证状态。 应用启动时,我在logcat窗口中看到了一些东西,
E/FirebaseInstanceId(10239): Failed to resolve target intent service, skipping classname enforcement
E/FirebaseInstanceId(10239): Error while delivering the message: ServiceIntent not found.
下面是我的代码:
main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import './home.dart';
import './orders.dart';
import './account.dart';
import './login.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyTabs(),
debugShowCheckedModeBanner: false,
routes: <String,WidgetBuilder>{
'/login':(BuildContext context) => Login()
},
theme: ThemeData(
primaryColor: Colors.white,
primaryColorDark: Colors.grey,
accentColor: Colors.green
),
);
}
}
class MyTabs extends StatefulWidget {
@override
_MyTabsState createState() => _MyTabsState();
}
class _MyTabsState extends State<MyTabs> {
FirebaseAuth auth = FirebaseAuth.instance;
int selectedIndex = 0;
final pages = [Home(),Orders(),Account()];
void choosePage(int index){
setState(() {
selectedIndex = index;
});
}
@override
void initState() {
super.initState();
if(auth.currentUser() == null){
Navigator.of(context).pushReplacementNamed("/login");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Tiffino")
),
body: pages[selectedIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedIndex,
fixedColor: Colors.black,
onTap: choosePage,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("Home")
),
BottomNavigationBarItem(
icon: Icon(Icons.list),
title: Text("Orders")
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text("Account")
)
]
)
);
}
}
如果我在上面的代码中做错了什么,请纠正我。
谢谢
答案 0 :(得分:1)
auth.currentUser()
方法返回一个Future,这意味着您应该使用then()
方法或异步方法中的await
运算符来解析它,而不是立即检查它是否为null。 ##标题##
尝试使用异步调用,而不是使用then和catchError,这将导致调用更多方法:
@override
void initState() {
super.initState();
_getCurrentUser();
}
/// Checks if the user is logged in
_getCurrentUser() async {
//Notice here the await operator, instead of using then() etc.
FirebaseUser mCurrentUser = await auth.currentUser();
if(mCurrentUser != null){
authSuccess(mCurrentUser);
} else {
// not logged in
Navigator.of(context).pushReplacementNamed("/login");
}
}
void authSuccess(FirebaseUser user){
// User is logged in, do something if needed
}