0

使用 FirebaseAuth 我正在尝试将 google 帐户注册到我的应用程序。

在我的主屏幕上,我单击 TextButton 导航到ConnectionPage,在初始使用时,它会将我转移到SignUpWidget,单击以使用 google 登录,它会弹出允许我选择我的 google 用户的 POPUP 窗口,此时应该被路由到LoggedInWidget但是什么也没有发生(即快照没有数据)并且我不断收到带有错误日志“I/flutter(721):类型'Future< GoogleSignInAccount?>'的SignUpWidget不是'GoogleSignInAccount'类型的子类型?” 在类型转换中"

GoogleSignInProvider 中某处存在转换错误,我无法解决。有什么帮助吗?

谢谢你。

==== 相关依赖 ====

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

代码片段

==== 谷歌登录提供商 ====

//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();
  }
}

==== 连接页面 ====

//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();
            }
          }),
    );
  }
}

==== 注册小工具 ====

//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(),
            ),
          ],
        ),
      ),
    );
  }
}
4

1 回答 1

1

在这一行中,您缺少一个await,这就是错误消息的含义。改变这个:

final googleUser = googleSignIn.signIn();

对此:

final googleUser = await googleSignIn.signIn();
于 2022-01-09T07:44:14.123 回答