-1

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 ? or when i add a null check when i add !.

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.

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 ?

 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')
                  //   ),
                  //);
                },
              ),
            )
          ],
        ),
      )
    ],
  ),
);
  }
 }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
wiem BM
  • 9
  • 1
  • Does this answer your question? [The method '\[\]' can't be unconditionally invoked because the receiver can be 'null'](https://stackoverflow.com/questions/67575893/the-method-cant-be-unconditionally-invoked-because-the-receiver-can-be-nu) – krishnaacharyaa Jan 14 '23 at 16:24

1 Answers1

1

The error is pretty clear: since your value is a DocumentSnapshot, its value.data() property is an Object?. The ? here means that data() can return null, which your code needs to handle.

A good way to tell your code what to do when value.data() is null is to use the ? 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.


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. You're handling that Future with then, but your .then((value) => ...) code will never render the 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");
  }
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807