I'm trying to build a listview in flutter and the itembuilder needs a return statement in order for it to display on the screen. But I have some problem when it comes to conditioning statement. My goal is I want to make the even buttons have a darker background. I've tried this code inside the body of the scaffold
body: ListView.builder(
itemCount: 20,
itemBuilder: (context, index){
//This is the condition with if else statement
if(index % 2 == 0){
return Card(
child: ListTile(
title: Text('${index+1}'),
onTap: (){
print('Clicked');
},
),
);
}else{
return Card(
color: Colors.grey[300],
child: ListTile(
title: Text('${index + 1}'),
onTap: () {
print('Clicked');
},
),
);
}
},
)
This code works. But the else if statement doesn't work. Just like this
body: ListView.builder(
itemCount: 20,
itemBuilder: (context, index){
if(index % 2 == 0){
return Card(
child: ListTile(
title: Text('${index+1}'),
onTap: (){
print('Clicked');
},
),
);
}//This statement triggers an error
else if(index % 2 == 1){
return Card(
color: Colors.grey[300],
child: ListTile(
title: Text('${index + 1}'),
onTap: () {
print('Clicked');
},
),
);
}
},
)
There are error because in an if else statement, there is no guarantee that one of the ifs will run. How can I assure flutter that I'm returning something in that clause because I'm afraid in my later projects if I will encounter this kind of problem whenever I really need else if statement. Please respect my question.
Aucun commentaire:
Enregistrer un commentaire