Home > other >  The operator '[]' isn't defined for the type 'Object'. Try defining the ope
The operator '[]' isn't defined for the type 'Object'. Try defining the ope

Time:08-20

before puting "!", I was getting this error:

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

This is my code:

FutureBuilder(
                  future: getCity(),
                  builder: ((context, snapshot) {
                    if (snapshot.hasData) {
                      var DocData = snapshot.data;

                      print(DocData);
                      return ListView.builder(itemBuilder: ((context, index) {
                        final String? title = DocData["Cities"];
                        return Text("testing");
                      }));
                    }
                    return Text('Loading...');
                  }))
            ],
          ),
        ),
      ),
    );
  }

  Future getCity() async {
    var doc = await FirebaseFirestore.instance
        .collection('Listing')
        .doc('City')
        .get();
    return doc.data();
  }

and this is my firestore database structure:

enter image description here

Data I am getting on Print call:

{Cities: {Islamabad: [{Price: 100000, Title: Apartment}, {Price: 200000, Title: House}], Mirpur: [{Price: 300000, Title: House}]}}

I want to show this data in my listview builder

CodePudding user response:

use ! after checking null.

 if (snapshot.hasData) {
   var DocData = snapshot.data as Map?;  
    return ListView.builder(itemBuilder: ((context, index) {
     final String? title = DocData?["Cities"];
     return Text("testing ${title}");
 }));
  • Related