简体   繁体   English

无法无条件调用方法“[]”,因为接收者可以为“null”。 flutter firebase

[英]The method '[]' can't be unconditionally invoked because the receiver can be 'null'. flutter firebase

I couldn't retrieve the data from another screen from an item within a list view using flutter and firebase. I keep having this error even if add a call condition using ?我无法使用 flutter 和 firebase 从列表视图中的项目中的另一个屏幕检索数据。即使使用添加调用条件,我仍然遇到此错误? or when i add a null check when i add !或者当我添加 null 时检查! . .

I am trying to add a comment on an item from a list view in another screen and to do that i tried to retrieve the title of the item.我正在尝试从另一个屏幕的列表视图中添加对某个项目的评论,为此我尝试检索该项目的标题。 Then when the user adds a comment, the comment will be added in the firestore with in a document that has the title of the item and the comment.然后,当用户添加评论时,评论将添加到 firestore 中,并添加到包含项目标题和评论的文档中。

The problem is that i get that error in this line:问题是我在这一行中得到了那个错误:

then((value) => value.data()["titre"])

I tried adding !我尝试添加! or ?或者? , but it just didn't work the problem keeps occurring. ,但它只是不起作用,问题不断发生。 There were people who said that I should transform me to then((value) =\> value.data\["titre"\]) , but with no clue can someone help me solve it?有人说我应该将我转换为then((value) =\> value.data\["titre"\]) ,但不知道有人能帮我解决吗?

 import 'package:cloud_firestore/cloud_firestore.dart';
 import 'package:flutter/material.dart';
 import 'package:flutter/src/widgets/container.dart';
 import 'package:flutter/src/widgets/framework.dart';

 class add_comment extends StatefulWidget {
 final DocumentReference docRef;
 const add_comment({key, required this.docRef, required titre})
  : super(key: key);

 @override
 State<add_comment> createState() => _add_commentState();
 }

class _add_commentState extends State<add_comment> {
  TextEditingController commentController = TextEditingController();
 @override
  Widget build(BuildContext context) {
   return Scaffold(
    body: Column(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Container(
        padding: EdgeInsets.all(5),
        child: Row(
          children: [
            Expanded(
                child: TextFormField(
              controller: commentController,
              minLines: 1,
              maxLength: 5,
              decoration: InputDecoration(
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(15))),
            )),
            SizedBox(
              width: 5,
            ),
            CircleAvatar(
              radius: 25,
              backgroundColor: Colors.green,
              child: IconButton(
                icon: Icon(Icons.send, color: Colors.white),
                onPressed: () async {
                  final Map<String, dynamic> commentData = {
                    'title': widget.docRef
                        .get()
                        .then((value) => value.data()["titre"]),
                    'text': commentController.text,
                  };
                  await FirebaseFirestore.instance
                      .collection('comments')
                      .doc(widget.docRef.id)
                      .collection('comments')
                      .add(commentData);
                  // Clear the comment text field
                  commentController.clear();
                  // Show a message to the user
                  // Scaffold.of(context).showSnackBar(
                  //   SnackBar(content: Text('Comment added')
                  //   ),
                  //);
                },
              ),
            )
          ],
        ),
      )
    ],
  ),
);
  }
 }

The error is pretty clear: since your value is a DocumentSnapshot , its value.data() property is an Object?错误很明显:因为您的valueDocumentSnapshot ,所以它的value.data()属性是Object? . . The ?? here means that data() can return null, which your code needs to handle.这里意味着data()可以返回 null,您的代码需要处理它。

A good way to tell your code what to do when value.data() is null is to use the ?value.data()为 null 时告诉您的代码该做什么的一个好方法是使用? coalescing and ??合并和?? operators:运营商:

value.data()?["titre"] ?? "no data found"

So here we say that, if value.data() is null, we'll return "no data found" instead.所以在这里我们说,如果value.data()是 null,我们将返回“找不到数据”。


There are more problems in your code though.但是,您的代码中存在更多问题。 Since you're calling widget.docRef.get() , that data is loaded from the database and is an asynchronous operation that returns a Future .由于您正在调用widget.docRef.get() ,因此该数据是从数据库加载的,并且是返回Future的异步操作。 You're handling that Future with then , but your .then((value) =>...) code will never render the value.您正在使用then处理 Future ,但是您的.then((value) =>...)代码永远不会呈现该值。

I recommend first checking whether the code actually works, by printing the value from the database:我建议首先通过打印数据库中的值来检查代码是否实际工作:

.then((value) => {
  print(value.data()?["titre"] ?? "no data found");
})

Or since it is now a block of code, we can use more readable constructs than ?或者因为它现在是一个代码块,我们可以使用比? and ???? and get the same result with:并得到相同的结果:

.then((doc) => {
  if (doc != null) {
    var value = doc!
    print(value["titre"]);
  } else {
    print("no data found");
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter 方法'[]'不能被无条件调用,因为接收者可以是'null' - Flutter The method '[]' can't be unconditionally invoked because the receiver can be 'null' 方法 '[]' 不能无条件调用,因为接收者可以是 'null' | Firebase 数据库 | Flutter - The method '[]' can't be unconditionally invoked because the receiver can be 'null' | Firebase Database | Flutter Listview Firebase Flutter 无法无条件调用方法“[]”,因为接收者可以为“null” - Listview Firebase Flutter The method '[]' can't be unconditionally invoked because the receiver can be 'null' 方法[]不能无条件调用,因为接收者可以是null - The method [] can't be unconditionally invoked because the receiver can be null 无法无条件调用方法“forEach”,因为接收者可以为“null” - The method 'forEach' can't be unconditionally invoked because the receiver can be 'null' 无法无条件调用方法“[]”,因为接收者可以为“null”。 错误 - The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Error 无法无条件调用方法“[]”,因为接收者可以为“null” - The method '[]' can't be unconditionally invoked because the receiver can be 'null' Flutter + Firestore 错误:无法无条件调用方法“[]”,因为接收器可以为“null” - Flutter + Firestore error: The method '[]' can't be unconditionally invoked because the receiver can be 'null' 无法无条件调用方法“[]”,因为接收者可以为“null”。 我在此代码中收到此错误 - The method '[]' can't be unconditionally invoked because the receiver can be 'null'. I am getting this error in this code 无法无条件调用方法“[]”,因为接收者可以为“null”,这是什么问题 - The method '[]' can't be unconditionally invoked because the receiver can be 'null' what is the problem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM