I’m new in Flutter journey.
I can use use ternary operator to set icon for 2 cases but I need to set Icon for multiple conditions. So, I need to use if or case statement. How can I do that.
I’m adding code as well as screen shoot. Kindly help.
Code
inputDecoration(title){
return InputDecoration(
prefixIcon:
if(title == 'title'){
Icon(Icons.title_outlined)
}
if(title == 'description'){
Icon(Icons.description),
},
//prefixIcon: title =='title' ? const Icon(Icons.title_outlined) : const Icon(Icons.description),
prefixIconColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
if(states.contains(MaterialState.focused)){
return Colors.green;
}if (states.contains(MaterialState.error)){
return Colors.red;
}
return Colors.grey;
}),
border: const OutlineInputBorder(
gapPadding: 15,
borderRadius: BorderRadius.all(Radius.circular(3))
)
);
}
2
Answers
You can use ternary operators or a switch statement.
Dart 3 switch expression:
I do not think that the syntax is acceptable if you were doing an if condition using
if(){}
inside the constuctor, instead you could set this logic before the build.Example:
or, you could use the ternary operator