0

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
}

2 Answers 2

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use `if-case` now (as of dart 3.9.0):

if (false) {
    // do nothing
}
else if (Provider().getNewMessages() case final messages when messages.isNotEmpty) {
    print("${messages.length} messages found!");
} 
else {
    print("No messages found!");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.