升级Flutter依赖后GoogleSignIn无默认构造函数报错求助
升级Flutter依赖后GoogleSignIn无默认构造函数报错求助
嗨,这个问题我之前升级google_sign_in包的时候也碰到过!这是因为新版本的google_sign_in库已经移除了默认的无参/带参构造函数,必须使用官方提供的命名构造函数来实例化对象。
问题原因
在google_sign_in 6.0.0及以上的版本中,官方对API做了兼容性变更——原来的GoogleSignIn(scopes: [...])这种默认构造函数写法已经被废弃并移除,取而代之的是命名构造函数来规范实例化方式。
解决步骤
只需要把你代码里实例化GoogleSignIn的那一行修改一下就行:
原来的代码:
final googleSignIn = GoogleSignIn(scopes: ['email']);
修改为:
final googleSignIn = GoogleSignIn.standard(scopes: ['email']);
如果你不需要指定额外的权限作用域,也可以直接简化成:
final googleSignIn = GoogleSignIn.standard();
修改后的完整代码示例
import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Google Sign-In Test', home: SignInTest(), ); } } class SignInTest extends StatefulWidget { const SignInTest({super.key}); @override State<SignInTest> createState() => _SignInTestState(); } class _SignInTestState extends State<SignInTest> { GoogleSignInAccount? _user; Future<void> _signIn() async { try { // 核心修改部分:使用命名构造函数实例化 final googleSignIn = GoogleSignIn.standard(scopes: ['email']); final account = await googleSignIn.signIn(); setState(() => _user = account); } catch (e) { print('Sign-in error: $e'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Google Sign-In Test')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_user != null) Text('Signed in: ${_user!.displayName}') else ElevatedButton( onPressed: _signIn, child: const Text('Sign in with Google'), ), ], ), ), ); } }
额外排查建议
如果修改后还是有报错,可以试试:
- 执行
flutter clean清理项目缓存,再运行flutter pub get重新拉取依赖 - 确认你的
pubspec.yaml里google_sign_in的版本是最新稳定版(可以运行flutter pub upgrade google_sign_in单独升级这个包)
内容来源于stack exchange
相关产品推荐
相关产品推荐

