Home > Software design >  the method[] cant be unconditionally invoked because the receiver can be null. i am trying to read d
the method[] cant be unconditionally invoked because the receiver can be null. i am trying to read d

Time:05-23

this is part of my product provider that i am calling on the homepage to return images and text to the screen. inside the product funtion at the element.data() i have tried to replace it with element.get('field value')the error disappears but nothing is written to the screen. im certain the issue is with null safety but adding ? or ! toelement.data?() or element.data!() solves nothing. i dont know whta else to do kindly offer any insight

 List<Product> homeFeature = [];
  late Product homeFeaturedata;
  Future<void> gethomefeaturedata() async {
    List<Product> newlist = [];
    QuerySnapshot homeFeaturesnapshot =
        await FirebaseFirestore.instance.collection("homefeature").get();   
    homeFeaturesnapshot.docs.forEach((element) {
      var homeFeaturedata = Product(
          image: element.data()["image"],
          name: element.data()["name"],
          price: element.data()["image"]);
      newlist.add(homeFeaturedata);
    });

    homeFeature = newlist;
  }

  List<Product> get gethomefeaturelist {
    return homeFeature;
    
  }


[enter image description here][1]


  [1]: https://i.stack.imgur.com/wVveO.png

This is part of the homepage where i will be calling the data from the querysnapshot

 Row(
        children: homeFeaturedProduct.map((e) {
          return Expanded(
            child: Row(children: [
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    Navigator.of(context).pushReplacement(
                      MaterialPageRoute(
                          builder: (context) => DetailView(
                              image: e.image, price: e.price, name: e.name)),
                    );
                  },
                  child: SingleProduct(
                      image: e.image, price: e.price, name: e.name),
                ),
              ),
              GestureDetector(
                  onTap: (() {
                    Navigator.of(context).pushReplacement(
                      MaterialPageRoute(
                          builder: (context) => DetailView(
                              image: e.image, price: e.price, name: e.name)),
                    );
                  }),
                  child: SingleProduct(
                    image: e.image,
                    price: e.price,
                    name: e.name,
                  )),
                  
            ]),
          );
        }).toList(),
      )

CodePudding user response:

The bang operator (the exclamation mark) should come after the method call. So your case, data!() should actually be data()!.

Aside from that, I would suggest that if you use the same method more than once in an enclosure, it's better to take it out into a variable. Like so:

final feature = element.data()!;
newList.add(Product(
  image: element.data()["image"],
  name: element.data()["name"],
  price: element.data()["image"],
));

As a side note, you should pay attention to your naming convention. Dart recommends using camelCase for variables (and your IDE should have alerted you to this as well). For example, homeFeaturedata should be homeFeatureData, and gethomefeaturedata should be getHomeFeatureData.

Lastly, I don't think you need the late Product homeFeaturedata; statement, as it is not used outside of the foreach scope. Just replace the var with final.

CodePudding user response:

This is the error im getting now

E/flutter (27943): [ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: Bad state: field does not exist within the
DocumentSnapshotPlatform, stack trace: #0      DocumentSnapshotPlatform.get._findKeyValueInMap
(package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:87:7)
[        ] E/flutter (27943): #1      DocumentSnapshotPlatform.get._findComponent
(package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:105:23)
[        ] E/flutter (27943): #2      DocumentSnapshotPlatform.get
(package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:121:12)
[        ] E/flutter (27943): #3      _JsonDocumentSnapshot.get (package:cloud_firestore/src/document_snapshot.dart:92:48)
[        ] E/flutter (27943): #4      ProductProvider.gethomefeaturedata.<anonymous closure>
(package:crommerce/views/commerce/provider/product_provider.dart:46:23)
[        ] E/flutter (27943): #5      List.forEach (dart:core-patch/growable_array.dart:416:8)
[        ] E/flutter (27943): #6      ProductProvider.gethomefeaturedata 

This is the code now

  List<Product> homeFeature = [];
  late Product homeFeaturedata;
  Future<void> gethomefeaturedata() async {
    List<Product> newlist = [];
    QuerySnapshot homeFeaturesnapshot =
        await FirebaseFirestore.instance.collection("homefeature").get();

    homeFeaturesnapshot.docs.forEach((element) {
      homeFeaturedata = Product(
        image: element.data().toString().contains('image')
            ? element.get("image")
            : '',
        name: element.data().toString().contains('name')
            ? element.get('name')
            : '',
        price: element.data().toString().contains('price')
            ? element.get('price')
            : 0,
      );
      newlist.add(homeFeaturedata);
    });
    homeFeature = newlist;
  }

  List<Product> get gethomefeaturelist {
    return homeFeature;
  }
  • Related