So I have updated the Flutter SDK and my swtich case functions work the same but now the break;
after each case in considered as dead code. I wonder why is that? I tried removing the return
statement but then the UI won't switch/change when the right parameter is achieved. The code:
Old Switch case statement before the update:
panelButtonsChange() {
switch (Provider.of<Store>(context).panelButtons) {
case 1:
return SomeClassButton(
onPressed: () {
store.setNumber(2);
},
buttonTitle: "Action 1",
);
break;
case 2:
return SomeClassButton(
onPressed: () {
store.setNumber(3);
},
buttonTitle: "Action 2",
);
break;
case 3:
return SomeClassButton(
onPressed: () {
store.setNumber(4);
},
buttonTitle: "Action 3");
break;
}
return SomeClassButton(
onPressed: () {
store.setNumber(1);
},
buttonTitle: "Default action",
);
}
Same Switch case statement but after the update to null safety (SDK >=2.12.0
):
panelButtonsChange() {
switch (Provider.of<Store>(context).panelButtons) {
case 1:
return SomeClassButton(
onPressed: () {
store.setNumber(2);
},
buttonTitle: "Action 1",
);
break; // THIS IS NOW DEAD CODE
case 2:
return SomeClassButton(
onPressed: () {
store.setNumber(3);
},
buttonTitle: "Action 2",
);
break; // THIS IS NOW DEAD CODE
case 3:
return SomeClassButton(
onPressed: () {
store.setNumber(4);
},
buttonTitle: "Action 3");
break; // THIS IS NOW DEAD CODE
}
return SomeClassButton(
onPressed: () {
store.setNumber(1);
},
buttonTitle: "Default action",
);
}
If I remove the return
statement in the new updated switch case, then the problem is that the buttons won't change in the UI because it is missing the return
statement. Is break;
now deprecated or am I missing something here? The weird part is that it still works normally like it use to, but I'm not sure if it was meant to work that way and should I remove the dead code or not.. Thanks in advance for your help.
UPDATE: Case where I don't use the return
but execute an action (in this case call an API):
switch (buttonNumber) {
case 0:
SomeActionClass(context).fetchAPI();
break;
case 1:
SomeActionClass(context).fetchOtherAPI();
break;
case 2:
SomeActionClass(context).fetchYetAnotherAPI();
break;
}
Here I have no return statement but the API calls are executed based on the case that is met.
CodePudding user response:
It says so because each break
after the return
will never be actually executed. I mean, any code after a return
will never get executed, and break
is no exception. You can simply remove the breaks, and your code won't even notice. The switch
will behave as before, because when it will find a relevant case
, the function will return
and the other cases won't be evaluated.