Home > Net >  Initialize variable in if condition - Flutter/Dart
Initialize variable in if condition - Flutter/Dart

Time:11-30

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:

  1. Calling it unless the first condition is false.
  2. Calling it twice, once to fetch the data to check the conditional & once to use the data inside the condition
  3. 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
}
  •  Tags:  
  • dart
  • Related