Caramel
Caramel

Reputation: 121

Flutter Qs : The getter 'length' was called on null

So I already make Condition where if the data called is null so it will Show No Data but it still have an Error.

Here's the code

Center(
            child: ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  if (data[index] == null) {
                    return Container(
                        child: Center(
                            child: Text(
                                "No News"
                            )
                        )
                    );
                  } else {
                    return GestureDetector(
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(
                            builder: (context) =>
                                DetailNewsScreen(
                                  data: data[index],
                                )));
                      },
                      child: Card(
                        child: Row(

but it still show error

Upvotes: 1

Views: 412

Answers (2)

Larvouu
Larvouu

Reputation: 162

You have to check if your data variable is null, otherwise you cannot call data.length as the itemCount

You're currently checking if data[index] is not null but not data itself

You could try :

Center(
            child: ListView.builder(
                itemCount: data == null ? 0 : data.length,
                itemBuilder: (BuildContext context, int index) {
                  if (data[index] == null) {
                    return Container(child: Center(child: Text("No News")));
                  } else {
                    // return whatever widget you want
                  } 
                }),
          ),

Upvotes: 3

Antoniossss
Antoniossss

Reputation: 32507

the data is null, not data[someIndex]

itemCount: data.length,

You didnt cover the case where data==null. The most straightforward way of fixing it, is to assing empty array.

if(data==null) data=[]; somewhere prior building the view.

Upvotes: 1

Related Questions