简体   繁体   中英

Google Sign-In error: type 'Future<GoogleSignInAccount?>' is not a subtype of type 'GoogleSignInAccount?' in type cast

Using FirebaseAuth I'm trying to get google account registration to my app.

on my home screen I click on a TextButton to navigate to the ConnectionPage , which on initial use, transfers me to the SignUpWidget , click to sign in with google and it pops the POPUP window allowing me to select my google user, at this point should be Routed to the LoggedInWidget however nothing happens (ie snapshot has no data) and I keep getting the SignUpWidget with error log "I/flutter ( 721): type 'Future<GoogleSignInAccount?>' is not a subtype of type 'GoogleSignInAccount?' in type cast"

There's a casting error somewhere in the GoogleSignInProvider, which im not able to resolve. any help?

Thank you.

==== Related Dependencies ====

# Google SignIn
  firebase_auth: ^3.2.0
  google_sign_in: ^5.2.1
# Google Icon
  font_awesome_flutter: ^9.2.0

code snippets

==== GoogleSignIn Provider ====

//LIBRARIES

//PACKAGES
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

//PAGES


//utilizing Provider dependency
class GoogleSignInProvider extends ChangeNotifier {
  //class implements the logic of the google sign in when clicking on google sign in button at the SignUpWidget
  final googleSignIn = GoogleSignIn();

  GoogleSignInAccount? _user; // the user that has signed in
  GoogleSignInAccount get user => _user!;

  Future googleLogin() async {
    try {
      final googleUser = googleSignIn
          .signIn(); // user account = account selected in login pop up
      // ignore: unnecessary_null_comparison
      if (googleUser == null) return;
      _user =
          googleUser as GoogleSignInAccount?; // saving account in _user field
      final googleAuth =
          await _user?.authentication; //getting accessToken and IdToken
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth!.accessToken,
        idToken: googleAuth.idToken,
      );

      await FirebaseAuth.instance.signInWithCredential(credential); // use credentials to sign into firebaseAuth
    } catch (e) {
      print(e.toString());
    }
    notifyListeners(); // updates the UI
  }

  Future logout() async {
    await googleSignIn.disconnect();
    FirebaseAuth.instance.signOut();
  }
}

==== CONNECTION PAGE ====

//PACKAGES
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

//PAGES
import '../data/vars.dart';
import '../widget/sign_up_widget.dart';
import '../widget/logged_in_widget.dart';

class ConnectionPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: BG_COLOR,
      body: StreamBuilder(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (context, snapshot) {
            // case: connection is waiting
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: LinearProgressIndicator());
            }
            // case: connection has error
            else if (snapshot.hasError) {
              return Center(
                child: Text(
                  'Something Went Wrong',
                  style: Theme.of(context).textTheme.headline1!.copyWith(),
                ),
              );
            }
            //case: user is logged in already
            else if (snapshot.hasData){
              return LoggedInWidget();
            }
            // case: user is not logged in
            else {
              return SignUpWidget();
                //SignUpWidget();
            }
          }),
    );
  }
}

==== SIGNUPWIDGET ====

//LIBRARIES

//PACKAGES
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

//PAGES
import '../data/vars.dart';
import '../provider/google_sign_in.dart';

class SignUpWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final data = MediaQuery.of(context);
    return Scaffold(
      appBar: AppBar(backgroundColor: BG_COLOR,),
      body: Container(
        color: BG_COLOR,
        height: data.size.height,
        width: data.size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            buildSignUp(context),
          ],
        ),
      ),
    );
  }

    Widget buildSignUp(BuildContext context) =>
        ElevatedButton.icon(
          onPressed: () {
            final provider = Provider.of<GoogleSignInProvider>(context,
                listen: false); // implemented in Provider package
            provider
                .googleLogin(); // user provider to call googleLogin method
          },
          style: Theme
              .of(context)
              .elevatedButtonTheme
              .style!
              .copyWith(),
          label: Text('Google Sign In'),
          icon: FaIcon(FontAwesomeIcons.google, color: Colors.white70,),
        );

}

==== LoggedInWidget ====

//LIBRARIES
//import 'dart:js';

//PACKAGES

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

//PAGES
import '../data/vars.dart';
import '../provider/google_sign_in.dart';

class LoggedInWidget extends StatelessWidget {
  //final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    final data = MediaQuery.of(context);
    final user = FirebaseAuth.instance.currentUser!;
    return Scaffold(
      appBar: AppBar(
        title: Text('Logged In'),
        centerTitle: true,
        actions: [
          TextButton(
              onPressed: () {
                final provider = Provider.of<GoogleSignInProvider>(context, listen:false);
                provider.logout();
              },
              child: Text('Log Out')
          )
        ],
      ),
      body: Container(
        height: data.size.height,
        width: data.size.width,
        padding: EdgeInsets.all(16.0),
        decoration: BoxDecoration(
          color: BG_COLOR,
          border: Border.all(
              width: 3.0, color: Colors.grey, style: BorderStyle.solid),
        ),
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Profile',
              style: Theme.of(context).textTheme.headline1!.copyWith(),
            ),

            //Display Avatar
            SizedBox(
              height: 20,
            ),
            CircleAvatar(
              radius: 50,
              backgroundImage: NetworkImage(user.photoURL!),
            ),

            //Display Name
            SizedBox(
              height: 8,
            ),
            Text(
              'Name: ' + user.displayName!,
              style: Theme.of(context).textTheme.caption!.copyWith(),
            ),

            //Display Email
            SizedBox(
              height: 8,
            ),
            Text(
              'Email: ' + user.email!,
              style: Theme.of(context).textTheme.caption!.copyWith(),
            ),
          ],
        ),
      ),
    );
  }
}

In this line you are missing an await , that's what the error message is about. Change this:

final googleUser = googleSignIn.signIn();

to this:

final googleUser = await googleSignIn.signIn();

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