0

How can get array data from firebase store?

Format

enter image description here

I used this code, but it will got error.

Exception has occurred. NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("postImages"))

getImages() async {
    var _firestoreInstance = FirebaseFirestore.instance;
    DocumentSnapshot<Map<String, dynamic>> qn =
        await _firestoreInstance.collection('Posts').doc(widget.postid).get();
    setState(() {
      for (int i = 0; i < qn.data()!.length; i++) {
        images.add(qn.data()![i]["postImages"]);
      }
    });
    return qn.data();
  }

also tried to used this methods, but still error.

final docSnapshot = await FirebaseFirestore.instance
        .collection('Posts')
        .doc(widget.postid)
        .get();
    final images = List<String>.from(docSnapshot.data()?['postImages'] ?? []);
    setState(() {
      images.addAll(images);
    });

Error code Exception has occurred. ConcurrentModificationError (Concurrent modification during iteration: Instance(length:2) of '_GrowableList'.)

Stanley
  • 311
  • 5
  • 15
  • I'm not sure but maybe `qn.data()!["postImages"][i]` ? because the `postImages` is a top level key in the `document`. And as far as I remember `data()` is called once for the document, it is not necessary to call it for the fields of the document. – Daniil Loban Jun 02 '22 at 03:05

1 Answers1

0

I see that you're getting one document and adding all instances of postImages to a list Images. The implementation was wrong I suppose.

Here's a updated code.

getImages() async {
    var _firestoreInstance = FirebaseFirestore.instance;
    DocumentSnapshot<Map<String, dynamic>> qn =
        await _firestoreInstance.collection('Posts').doc(widget.postid).get();
    
    data = qn.data() as Map<String,dynamic>;

    setState(() {
      for (int i = 0; i < qn.data()!.length; i++) {
        images.add(data["postImages"][i]);
      }
    });
    return qn.data();
  }
Delwinn
  • 891
  • 4
  • 19
  • I used this `Map data = qn.data() as Map;` then I got the this error `RangeError (RangeError (index): Invalid value: Not in inclusive range 0..1: 2)` – Stanley Jun 02 '22 at 12:20
  • if just used `data = qn.data() as Map;` it will get `Undefined name 'data'. Try correcting the name to one that is defined, or defining the name.` – Stanley Jun 02 '22 at 12:29
  • sorry, please update it to `Map data = qn.data() as Map;` – Delwinn Jun 02 '22 at 16:00