Ad

How To Assure Flutter That You Will Surely Triggers A Return Statement

- 1 answer

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.

Ad

Answer

There is no need for the second else if statement. If the num mod 2 isn't equal to 0 then it's definitely an odd number. Using else will solve your problem.

If you insist on using this, with different logic for a future project, you should do something like this

ListView.build(
  itemCount : 20,
  itemBuilder: (context, index) {
    if (condition1) {
      return Text("Condition 1 fulfilled!");
    } else if (condition2) {
      return Text("Condition 2 fulfilled!");
    }

    return Text("Incase no condition was fulfilled!");
}
Ad
source: stackoverflow.com
Ad