29:52: Error: Property 'photoURL' cannot be accessed on 'User?' because it is potentially null


I am trying to add google sign in with firebase auth in my basic flutter app, but I am getting above mentioned error. I searched alot but couldn’t found any answer, please help me out. This is the whole error in my terminal:

lib/logged_in_widget.dart:29:52: Error: Property 'photoURL' cannot be accessed on 'User?' because it is potentially null.
 - 'User' is from 'package:firebase_auth/firebase_auth.dart' ('../../../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.4.1/lib/firebase_auth.dart').
Try accessing using ?. instead.
                backgroundImage: NetworkImage(user.photoURL!),
lib/logged_in_widget.dart:34:32: Error: Property 'displayName' cannot be accessed on 'User?' because it is potentially null.
 - 'User' is from 'package:firebase_auth/firebase_auth.dart' ('../../../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.4.1/lib/firebase_auth.dart').
Try accessing using ?. instead.
                'Name:' + user.displayName!,

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Exception: Gradle task assembleDebug failed with exit code 1

I have done null safety too using:

dart pub outdated --mode=null-safety

This is the main code:

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

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

  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser;
    return Scaffold(
        appBar: AppBar(
          title: Text('Logged In'),
          centerTitle: true,
          actions: [
            TextButton(onPressed: () {}, child: Text('Logout'),)
        body: Container(
          alignment: Alignment.center,
          color: Colors.blueGrey.shade900,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('profile', style: TextStyle(fontSize: 24),),
              SizedBox(height: 32,),
                radius: 40,
                backgroundImage: NetworkImage(user.photoURL!),

              SizedBox(height: 8,),
                'Name:' + user.displayName!,
                style: TextStyle(color: Colors.white, fontSize: 16),

and this is the code in my firebase_auth file:

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

class GoogleSignInProvider extends ChangeNotifier{
  final googleSign = GoogleSignIn();

  GoogleSignInAccount? _user;

  GoogleSignInAccount get user => _user!;

  Future GoogleLogin() async {
    final googleUser = await googleSign.signIn();
    if (googleUser == null) return;
    _user = googleUser;

    final googleAuth = await googleUser.authentication;

    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,

    await FirebaseAuth.instance.signInWithCredential(credential);


and this is my pubspec.yaml file"

description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

  sdk: ">=2.15.1 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0
  cupertino_icons: ^1.0.2
  firebase_auth: ^1.1.4
  google_sign_in: ^5.0.3
  font_awesome_flutter: ^9.0.0
  provider: ^5.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages


Just as a side note:

  GoogleSignInAccount? _user;
  GoogleSignInAccount get user => _user!;

This is really not a great practice if you are not 100% certain that _user will never be null. But getting _user can got wrong, without returning any value.

To your question:

NetworkImage() requires a String (non-nullable type)! In your code NetworkImage(user.photoURL!), you are doing that by telling dart that it logically can never be null by using the bang operator (!).

The same is the case for displayName, since Text() also requires a String not a String? –> That is the whole point of nullsafety: To avoid null errors during run time.

Make sure GoogleSignInAccount? _user; is not null before referencing it anywhere
in your code.

Answered By – Jahn E.

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *