Home > OS >  Can someone explain me why I'm getting this runtime error in flutter
Can someone explain me why I'm getting this runtime error in flutter

Time:04-17

I am getting this runtime error although If I click the back button, then the screen gets navigated to the route I'm trying to redirect but before that this error screen always pops up.

Here's the code snippet:

 body: Container(
    child: FutureBuilder<DocumentSnapshot>(
    future: _service.categories.doc(args.id).get(),
       builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasError) {
          return Container();
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator(),);
        }

        var data = snapshot.data!['subCat'];
        return Container(
          child: ListView.builder(

            itemCount: data.length,
            itemBuilder: (BuildContext context, int index){

              return Padding(
                padding: const EdgeInsets.only(left: 8,right: 8),
                child: ListTile(
                  onTap: (){
                    //sub categories
                  },
                  title: Text(data[index],style: TextStyle(fontSize: 16),),
                ),
              );
            },
          ),
        );
      },
    ),
  ),

enter image description here

enter image description here

CodePudding user response:

You are handling error and loading state. Try checking data existence and then proceed of using this. In that case check data just after checking watting state.

if(!snapshot.hasData){
return Text("it doesnt Have any data");
}

I will encourage you not to use ! directly without checking null. In your case, it is on

var data = snapshot.data!['subCat'];

do

var data = snapshot.data?['subCat'];
if (data==null){
   return Text("subCat is empty");
}
///else move to list container

CodePudding user response:

It is because your "itemCount: data.length" does not have data to read. You can't invoke ".length" from a null instance.

Try to check whether your data is not null or whether it has values for the listView.builder can iterate.

  • Related