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

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

我正在尝试在我的基本 Flutter 应用程序中添加 google 使用 firebase 身份验证登录,但出现上述错误。我搜索了很多但找不到任何答案,请帮助我。这是我终端中的全部错误:

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

BUILD FAILED in 21s
Exception: Gradle task assembleDebug failed with exit code 1

我也使用了空安全:

dart pub outdated --mode=null-safety

这是主要代码:

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;

  @override
  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,),
              CircleAvatar(
                radius: 40,
                backgroundImage: NetworkImage(user.photoURL!),

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

这是我的 firebase_auth 文件中的代码:

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);

    notifyListeners();
  }
}

这是我的 pubspec.yaml 文件

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

environment:
  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`.
dependencies:
  flutter:
    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

dev_dependencies:
  flutter_test:
    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.
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

作为旁注:

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

如果您不能 100% 确定 _user 永远不会为 null,那么这确实不是一个好的做法。但是获取 _user 可能会出错,没有返回任何值。

你的问题:

NetworkImage() 需要一个 String不可为 null 的类型)!在您的代码 NetworkImage(user.photoURL!), 中,您通过使用 bang 运算符 (!) 告诉 dart 它在逻辑上永远不能为 null 来做到这一点。

displayName 也是如此,因为 Text()requires a String 不是字符串? --> 这就是 nullsafety 的全部要点:在 运行 时间内避免 null 错误。

解法: 确保GoogleSignInAccount? _user;在任何地方引用它之前不为空 在你的代码中。