Home > other >  Flutter - Firestore How to manage null value from a Future
Flutter - Firestore How to manage null value from a Future

Time:11-11

I need to check if data exist in document.

For example I want to know if itemOne in items map exist in check document. Here we have only price map. So it means ['items']['itemOne'] not exist.

enter image description here

I fetch data at the InitState with a Future and I cannot manage the following error :

NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: ["itemOne"]

I use this Future :

String itemOne = "";

  Future fetchData() async {
    try {
      await FirebaseFirestore.instance
          .collection('payment')
          .doc("check")
          .get()
          .then((DocumentSnapshot doc) {
        final Map<String, dynamic> data = doc.data() as Map<String, dynamic>;

        itemOne = data['items']['itemOne'];
        
        
      }).then((value) => setState(
                () => isLoading = false,
              ));
    } catch (e) {
      print(e);
    }
  }

How to manage this error and replace value if the string "itemOne" receive null value?

I tried to use this type of code in the Future :

itemOne = data['items']['itemOne'] ?? "Not Found";

But this is not working.

CodePudding user response:

You first need to check if data['items'] is null or not.

itemOne = data['items'] != null ? data['items']['itemOne'] ?? 'Not Found' : 'Not Found';

  • Related