Search code examples
flutterdartflutter-futurebuilder

The method '[]' was called on null. Receiver: null Tried calling: []("subcategory")


i am trying to get data from firebase using flutter with futurebuilder

this the code

FutureBuilder<DocumentSnapshot>(
          future: _services.category.doc(_provider.selectedCategory).get(),
          builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot){
            if(snapshot.hasError){
              return Text('something went wrong...');
            }
            if(snapshot.connectionState == ConnectionState.waiting){
              return Center(child: CircularProgressIndicator(),);
            }
            Map<String, dynamic>data = snapshot.data.data();
            return Expanded(
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(10),
                    child: Container(
                      child: Row(

                        children: [
                          Text('Main Category:   '),
                          FittedBox(
                              child: Text(_provider.selectedCategory,
                                style: TextStyle(fontWeight: FontWeight.bold),)),
                        ],
                      ),
                    ),
                  ),
                  Divider(thickness: 3,),
                  Container(
                    child: Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(10),
                        child: ListView.builder(
                          itemCount: data['subcategory'] == null ? 0: data['subcategory'].length,
                            itemBuilder: (BuildContext context, int index){
                              return ListTile(
                                contentPadding: EdgeInsets.zero,
                                leading: CircleAvatar(
                                  child: Text('${index + 1}'),
                                ),
                                title: Text(data['subcategory'][index]['name']),
                                onTap: (){
                                  _provider.selectSubCategory(data['subcategory'][index]['name']);
                                  Navigator.pop(context);
                                },

_provider.selectedCategory come from another stream builder where user choose category based on the option that also come from firebase data

_services = CollectionReference category = FirebaseFirestore.instance.collection('categories');

but it seems that the document snapshot is empty

can anyone help me to solve this?? thank you


Solution

  • try adding if (snapshot.connectionState == ConnectionState.done&& snapshot.hasData && snapshot.data != null){return your widget; }