【问题标题】:Function can't be unconditionally invoked because it can be 'null'函数不能被无条件调用,因为它可以是'null'
【发布时间】:2021-11-12 19:30:40
【问题描述】:

我正在构建个人资料页面。但我在从 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()['username'],到:snapshot.data['username'],检查这个:stackoverflow.com/questions/64792658/…
  • snapshot.data['username'],没有工作,因为它显示'方法'[]'不能无条件调用,因为接收器可以是'null'。 '

标签: firebase flutter dart storage


【解决方案1】:

应该是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),
              ),
            ),

【讨论】:

  • 我认为您在第一行错过了“>”运算符。可以加吗?
  • 我希望它有效吗?
  • 错误:不能将参数类型“AsyncSnapshot>”分配给参数类型“AsyncSnapshot>>”。
  • .headerProfile(上下文,快照),^
  • 这是我在 profile.dart 文件中遇到的错误
【解决方案2】:

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

也可以参考这篇文章 link for fetching data from real time firebase DB

【讨论】:

  • snapshot.data['username'],没有工作,因为它显示'方法'[]'不能无条件调用,因为接收器可以是'null'。
猜你喜欢
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2022-01-08
  • 2022-08-24
  • 2022-08-15
  • 2023-04-10
  • 1970-01-01
  • 2022-08-15
相关资源
最近更新 更多