Is it possible to do something like the following? aka, initialize a variable inside an if statement condition?
Reasoning:
I have a network call that will fetch data, and I'd like to avoid the following options:
- Calling it unless the first condition is false.
- Calling it twice, once to fetch the data to check the conditional & once to use the data inside the condition
- Having to nest if statements
So initializing the variable inside the conditional block seems like the cleanest solution.
if (condition1) {
// Do something
} else if ( (String foo = await getBar()) == "not bar"){
// Do something with foo
} else {
// Fallback condition
}
CodePudding user response:
One option would be to declare the variable before the condition like so:
String foo; // Declare variable here
if (condition1) {
// Do something
} else if ((foo = await getBar()) == "not bar") {
// Do something with foo
} else {
// Fallback condition
}