Home > front end >  flutter:: Can I use conditional statements inside a button or widget?
flutter:: Can I use conditional statements inside a button or widget?

Time:10-05

This is my code. I want to get a variable called "favorite" from the Video0_02 file and change the color to yellow if true and to blue if false. I don't know how to write the code because the if statement doesn't work. How do I solve this?


    LearnLevelButton(
                      color: Colors.yellow,
                      onTap: () async {
                        await Navigator.push(
                            context, MaterialPageRoute(builder: (context) {
                          return Video0_02();
                          //Level newLevel = await gameBloc.setLevel(index   1);
                          //Navigator.of(context).push(GamePage.route(newLevel));
                        }));
                      },
                    ),

CodePudding user response:

Try with this


    LearnLevelButton(
                      color: favorite? Colors.yellow:Colors.blue,
                      onTap: () async {
                        await Navigator.push(
                            context, MaterialPageRoute(builder: (context) {
                          return Video0_02();
                          //Level newLevel = await gameBloc.setLevel(index   1);
                          //Navigator.of(context).push(GamePage.route(newLevel));
                        }));
                      },
                    ),

CodePudding user response:

There are several ways you can use to handle the logic.

  1. Use Dart's ternary operator. Something like this:
...
// Remember to check in case your `favorite` variable is null, set it to false
LearnLevelButton(
  color: (favorite ?? false) ? Colors.yellow : Colors.blue,
  ...
),
  1. Use a function to handle the logic:
LearnLevelButton(
  color: getColor(favorite),
  ...
),
// The function
Color getColor(bool favorite) {
  if (favorite ?? false) {
    return Colors.yellow;
  }
  return Colors.blue;
}

Other way is immediate anonymous function or use switch/case in your separate function when there are more than 2 values to consider. But these 2 methods should be enough to get you started! ;)

  • Related