简体   繁体   中英

Unable to navigate based on auth state in flutter-firebase

I am using firebase as a backend service in my android app.I am trying to navigate user to the login screen if it is not logged in.I am checking auth state in main.dart file. when app launches I am getting something in my logcat window like:

E/FirebaseInstanceId(10239): Failed to resolve target intent service, skipping classname enforcement
E/FirebaseInstanceId(10239): Error while delivering the message: ServiceIntent not found.

Below is my code:

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")
         )
        ]
      )      
    );
  }
}

Someone please correct me if I did anything wrong in above code.

THANKS

The auth.currentUser() method returns a Future, which means you should use a then() method to resolve it or the await operator in an async method, instead of instantly checking if it's null.## Heading ##

Try this with async calls, instead of using then and catchError, which would lead to a few more methods to be called:

@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
}

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