首页 > 解决方案 > 退出后无法登录 - Firebase Google Signin with Flutter

问题描述

我可以使用 Google 登录和退出。但是,当我重新登录时,我没有被重定向到我指定的页面。它卡在登录页面上。

这是登录按钮的 onPressed 方法:

 onPressed: () async {
        await Provider.of<Auth>(context, listen: false).signInWithGoogle();
  }, 

signInWithGoogle() 方法在下面的 Auth 类中。

这是 Auth 类:

class Auth with ChangeNotifier {
  String _token;
  String _userId;
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = GoogleSignIn();

  bool get isAuth {
    return token != null;
  }

  String get token {
    if(_token != null) 
      return _token; 
    return null;
  }

  String get userId {
    return _userId;
  }

  Future<void> signInWithGoogle() async {
    final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication =
        await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

    final UserCredential authResult =
        await _auth.signInWithCredential(credential);
    final User user = authResult.user;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final User currentUser = _auth.currentUser;

    assert(user.uid == currentUser.uid);
    print('User is ' + user.displayName); 
    
    _token = await currentUser.getIdToken(); 
    print('Token is ' + _token); 
    _userId = currentUser.uid;
     notifyListeners();
  }

  Future<void> signOutGoogle() async {
    await googleSignIn.signOut();
     _token = null;
     _userId = null;
    notifyListeners();
    print("User Sign Out");
  }

   Future<bool> tryAutoLogin() async {
   //will implement later 
      return false; 
   }
}

这是main.dart

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

class MyApp extends StatelessWidget {
  
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
       ChangeNotifierProvider(
          create: (_) => Auth(),
        ), 
       ChangeNotifierProxyProvider<Auth,Categories>(
          create:null,
         update:(ctx,auth, previousCategories) => Categories(auth.token, auth.userId)),
    ],

    //The consumer ensures that the material app gets built whenever Auth object changes
        child: Consumer<Auth>(builder: (ctx, auth, _) => 
          MaterialApp(
        title: 'MyShop',
        theme: ThemeData(
           textTheme: Theme.of(context).textTheme.apply(
            bodyColor: Colors.black,
            displayColor: Colors.black,
            ),
          primaryColor: Colors.orange,
          accentColor: Colors.deepOrange,
          fontFamily: 'Lato',
        ),
        home: auth.isAuth ?   CategoriesScreen()  
         : FutureBuilder(
                      future: auth.tryAutoLogin(),
                      builder: (ctx, authResultSnapshot) =>
                          authResultSnapshot.connectionState ==
                                  ConnectionState.waiting
                              ? SplashScreen()
                              : LoginPage(),
        ),
        routes: {
           CategoriesScreen.routeName: (ctx) => CategoriesScreen(),
           LoginPage.routeName: (ctx) => LoginPage()
        }
      ),
        ) 
    );
  }
}

这是注销按钮:

 ListTile(
            leading: Icon(Icons.exit_to_app),
            title: Text('Logout'),
            onTap: () {
            Provider.of<Auth>(context, listen:false).signOutGoogle(); 
            Navigator.of(context).pushReplacementNamed(LoginPage.routeName);
          
            },
          ),

当我第一次登录时,我被重定向到 CategoriesScreen() 页面。但是,当注销并重新登录时,我不会被重定向。

标签: firebaseflutterfirebase-authenticationgoogle-signin

解决方案


推荐阅读