Flutter项目Google登录网络异常处理优化:替换ApiException错误提示为友好网络错误信息
I get exactly where you're stuck here — when using Google Sign-In without internet, the thrown PlatformException spits out a technical, user-unfriendly message instead of the clean error prompts you get with email/phone login via FirebaseAuthException. Let's fix this by targeting the specific exception type and mapping it to a clear, readable error message.
Step 1: Update Google Sign-In Exception Handling
First, we need to stop catching a generic Exception and explicitly target PlatformException (since that's what your console log shows is being thrown). We can check the error code or message content to identify network errors, then pass a friendly message to your callback instead of the raw exception.
Here's the revised signInWithGoogle function:
import 'package:flutter/services.dart'; // Don't forget this import for PlatformException Future<void> signInWithGoogle( void Function(String errorMessage) errorCallback, // Adjust callback to accept a string message ) async { try { final GoogleSignInAccount? googleUser = await googleSignIn.signIn(); final GoogleSignInAuthentication? googleAuth = await googleUser!.authentication; final credential = GoogleAuthProvider.credential( accessToken: googleAuth!.accessToken, idToken: googleAuth.idToken, ); await FirebaseAuth.instance.signInWithCredential(credential); } on PlatformException catch (e) { String errorMessage; // Match the network error code or the ApiException 7 marker from your log if (e.code == 'network_error' || e.message?.contains('ApiException: 7') == true) { errorMessage = 'No internet connection. Please check your network and try again.'; } else { // Fallback for other Google Sign-In specific errors errorMessage = e.message ?? 'An error occurred during Google Sign-In.'; } errorCallback(errorMessage); } on FirebaseAuthException catch (e) { // Handle any Firebase auth errors that pop up during credential sign-in errorCallback(e.message ?? 'Authentication failed.'); } catch (e) { // Catch-all for unexpected issues errorCallback('An unexpected error occurred.'); } }
Step 2: Tweak the Error Dialog to Accept a Message String
Your current _showErrorDialog expects an Exception, but since we're now passing a friendly text message, let's adjust it to take a string directly for the content:
void _showErrorDialog(BuildContext context, String title, String errorMessage) { showDialog<void>( context: context, builder: (context) { return AlertDialog( title: Text( title, style: const TextStyle(fontSize: 24), ), content: SingleChildScrollView( child: ListBody( children: <Widget>[ Text( errorMessage, style: const TextStyle(fontSize: 18), ), ], ), ), actions: <Widget>[ ElevatedButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('OK', style: TextStyle(color: Colors.deepPurple)), ) ], ); }, ); }
Step 3: Update How You Trigger the Sign-In and Dialog
When calling Google Sign-In, pass a callback that triggers the dialog with the friendly message:
// Example usage in your UI code signInWithGoogle((errorMessage) { _showErrorDialog(context, 'Sign-In Error', errorMessage); });
Why This Works
- We're catching the exact
PlatformExceptiontype thrown by Google Sign-In, instead of a vague generic exception. - We check for the
network_errorcode or theApiException: 7marker (a known code for network issues in Google Play Services) to show a clear, user-centric message. - We've expanded coverage to handle Firebase auth errors that might happen when validating the Google credential, plus a safety net for unexpected edge cases.
Now when users try to sign in with Google offline, they'll see a clean "No internet connection" prompt instead of the confusing technical jargon.
内容的提问来源于stack exchange,提问作者Naveed Mir

