函数不能被无条件调用,因为它可以是 'null'

Function can't be unconditionally invoked because it can be 'null'

我正在构建个人资料页面。但是我在从 firebase 检索名称和邮件时遇到了一些问题。

 firebase_auth: ^3.1.1
 firebase_core: ^1.6.0
 google_sign_in: ^5.1.0
 firebase_storage: ^10.0.3
 cloud_firestore: ^2.5.3
 firebase_analytics: ^8.3.2
 lottie: ^1.1.0
 image_picker: ^0.8.4

以上是我的 pubspec.yaml 依赖项。

  Widget headerProfile(
  BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
  return SizedBox(
  height: MediaQuery.of(context).size.height * 0.26,
  width: MediaQuery.of(context).size.width,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Container(
        height: 150.0,
        width: 170.0,
        child: Column(
          children: [
            GestureDetector(
              onTap: () {},
              child: CircleAvatar(
                backgroundColor: constantColors.transparent,
                radius: 38.0,
                backgroundImage: NetworkImage(
                    '${Provider.of<FirebaseOperations>(context).getInitUserImage}'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text(
                snapshot.data()['username'],
                style: TextStyle(
                    color: constantColors.whiteColor,
                    fontWeight: FontWeight.bold,
                    fontSize: 20.0),
              ),
            ),

上面是 profilehelpers.dart 页面。

 class Profile extends StatefulWidget {
 @override
 _ProfileState createState() => _ProfileState();
 }

class _ProfileState extends State<Profile> {
final ConstantColors constantColors = ConstantColors();
 @override
 Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    centerTitle: true,
    leading: IconButton(
      onPressed: () {},
      icon: Icon(EvaIcons.settings2Outline,
          color: constantColors.lightBlueColor),
    ),
    actions: [
      IconButton(
          icon: Icon(EvaIcons.logOutOutline,
              color: constantColors.greenColor),
          onPressed: () {
            Provider.of<ProfileHelpers>(context, listen: false)
                .logOutDialog(context);
          })
    ],
    backgroundColor: constantColors.blueGreyColor.withOpacity(0.4),
    title: RichText(
      text: TextSpan(
          text: 'My ',
          style: TextStyle(
            color: constantColors.whiteColor,
            fontWeight: FontWeight.bold,
            fontSize: 20.0,
          ),
          children: <TextSpan>[
            TextSpan(
                text: 'Profile',
                style: TextStyle(
                  color: constantColors.blueColor,
                  fontWeight: FontWeight.bold,
                  fontSize: 20.0,
                ))
          ]),
       ),
      ),
    body: SingleChildScrollView(
    child: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
       
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: FirebaseFirestore.instance
              .collection('users')
              .doc(Provider.of<Authentication>(context, listen: false)
                  .getUserUid)
              .snapshots(),
          builder: (BuildContext context,
              AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return new Column(
                children: [
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .headerProfile(context, snapshot),
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .divider(),
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .middleProfile(context, snapshot),
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .footerProfile(context, snapshot)
                ],
              );
            }
          },
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15.0),
            color: constantColors.blueGreyColor.withOpacity(0.6)),
      ),
    ),
     ),
    );
    }
    }

以上是profile.dart文件代码。 我认为问题出在 document 和 asyncsnapshot 以及“snapshot.data()['username']”的某个地方。如果有人能指出我的错误,那将对我更有帮助。

40:34: Error: 'data' isn't a function or method and can't be 
  invoked.
                snapshot.data()['username'],
                             ^^^^


FAILURE: Build failed with an exception.

这是我遇到的错误

应该是snapshot.data.data()['username']而不是snapshot.data()['username']

由于您编写代码的方式,您可能仍然会遇到错误(例如 Object 不是 Map 的子类型),在这种情况下,请使用此(复制并粘贴到您的代码中) , 我改变了一些东西):

Widget headerProfile(
  BuildContext context, AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
  Map<String, dynamic>? map = snapshot.data!.data();
  return SizedBox(
  height: MediaQuery.of(context).size.height * 0.26,
  width: MediaQuery.of(context).size.width,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Container(
        height: 150.0,
        width: 170.0,
        child: Column(
          children: [
            GestureDetector(
              onTap: () {},
              child: CircleAvatar(
                backgroundColor: constantColors.transparent,
                radius: 38.0,
                backgroundImage: NetworkImage(
                    '${Provider.of<FirebaseOperations>(context).getInitUserImage}'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text(
                map['username'],
                style: TextStyle(
                    color: constantColors.whiteColor,
                    fontWeight: FontWeight.bold,
                    fontSize: 20.0),
              ),
            ),

你能试试“snapshot.data['username']”吗?

也参考这个post