Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Control Flow

Dart Control Flow

Control flow determines the order in which code in a program executes.

This chapter introduces conditional judgments (if/else, switch) and loop statements (for, while) in Dart, as well as the use of break and continue.


if / else / else if Conditional Judgment

The if statement is the most basic control flow structure; it decides whether to execute a block of code based on a condition.

Example

Basic if judgment:

void

main

(

)

{

 

int

score

=

85

;

 

// Basic if: executes when the condition is true

 

if

(

score

=

60

)

{

    print

(

'RUNOOB Congratulations, you passed!'

)

;

 

}

 

// if-else: choose one of two

 

if

(

score

=

90

)

{

    print

(

'Excellent'

)

;

 

}

else

{

    print

(

'Keep it up'

)

;

 

}

 

// if-else if-else: multi-branch selection

 

if

(

score

=

90

)

{

    print

(

'Level: A'

)

;

 

}

else

if

(

score

=

80

)

{

    print

(

'Level: B'

)

;

 

}

else

if

(

score

=

70

)

{

    print

(

'Level: C'

)

;

 

}

else

if

(

score

=

60

)

{

    print

(

'Level: D'

)

;

 

}

else

{

    print

(

'Level: F (Fail)'

)

;

 

}

}



RUNOOB 恭喜,你及格了!

继续加油

等级:B

Dart conditional expressions must be of type bool. You cannot use 0, '', null, etc. as conditions the way JavaScript does -- such usage will directly cause a compile error in Dart.

Nesting of if statements

You can nest if statements inside if statements to handle more complex logic.

Example

void

main

(

)

{

 

bool

isLoggedIn

=

true

;

 

bool

isAdmin

=

false

;

  String username

=

'runoob'

;

 

if

(

isLoggedIn

)

{

   

// Outer check: whether logged in

   

if

(

isAdmin

)

{

     

// Inner check: whether an administrator

      print

(

'Welcome back, admin $username'

)

;

   

}

else

{

      print

(

'Welcome back, $username'

)

;

   

}

 

}

else

{

    print

(

'Please log in first'

)

;

 

}

}



欢迎回来,runoob

Too many nesting levels reduce readability; no more than 3 levels are recommended.

If the logic is truly complex, consider using early return (return) or splitting into functions to simplify.

Example

Use early return instead of deep nesting:

// Use early return instead of deep nesting for better readability

String getAccessMessage

(

bool

isLoggedIn

,

bool

isAdmin

,

String name

)

{

 

// First handle the cases where we return if the condition is not met

 

if

(

!

isLoggedIn

)

{

   

return

'Please log in first'

;

 

}

 

if

(

!

isAdmin

)

{

   

return

'You do not have admin privileges'

;

 

}

 

// The main logic comes last

 

return

'Welcome back, admin $name'

;

}

void

main

(

)

{

  print

(

getAccessMessage

(

true

,

false

,

'runoob'

)

)

;

  print

(

getAccessMessage

(

true

,

true

,

'runoob'

)

)

;

}



你没有管理权限

欢迎回来,管理员 runoob


switch / case multi-branch selection

When a variable has several fixed possible values, switch is clearer than if-else if.

Example

void

main

(

)

{

  String day

=

'Wednesday'

;

 

switch

(

day

)

{

   

case

'Monday'

:

      print

(

'A new week has begun'

)

;

     

break

;

 

// break ends the current case, preventing fall-through to the next case

   

case

'Tuesday'

:

      print

(

'The struggle of the second day'

)

;

     

break

;

   

case

'Wednesday'

:

      print

(

'The week is half over'

)

;

     

break

;

   

case

'Thursday'

:

      print

(

'Almost Friday'

)

;

     

break

;

   

case

'Friday'

:

      print

(

'TGIF!'

)

;

     

break

;

   

case

'Saturday'

:

   

case

'Sunday'

:

     

// Multiple cases can share a block of code

      print

(

'Happy weekend!'

)

;

     

break

;

   

default

:

     

// Executed when no case matches

      print

(

'Unknown date'

)

;

 

}

}



一周过半了

Dart's switch does not automatically fall through; every non-empty case must end with break, return, throw, or continue. To achieve fall-through, use continue together with a label.

switch expression (Dart 3.0+)

Dart 3.0 introduced switch expressions, which can directly produce values with more concise syntax.

Example

void

main

(

)

{

  String day

=

'Wednesday'

;

 

// switch expression: returns a value directly

  String mood

=

switch

(

day

)

{

   

'Monday'

=>

'A bit sleepy'

,

   

'Tuesday'

=>

'Starting to adapt'

,

   

'Wednesday'

=>

'Full of energy'

,

   

'Thursday'

=>

'Looking forward to the weekend'

,

   

'Friday'

=>

'Feeling cheerful'

,

   

'Saturday'

||

'Sunday'

=>

'Carefree'

,

    _

=>

'Unknown'

 

// _ is a wildcard, equivalent to default

 

}

;

  print

(

'RUNOOB mood: $mood'

)

;

}



RUNOOB 心情: 干劲十足

switch expressions require covering all possible cases; the compiler checks for omissions for you.


for loop

The for loop is the most commonly used loop structure, suitable when the number of iterations is known.

Standard for loop

Example

void

main

(

)

{

 

// Standard for loop: initialization; condition; update

 

for

(

int

i

=

1

;

i

<=

5

;

i

++

)

{

    print

(

'RUNOOB iteration $i'

)

;

 

}

 

// The loop variable can also be declared outside

 

int

j

=

0

;

 

for

(

;

j

<

3

;

j

++

)

{

    print

(

'j = $j'

)

;

 

}

}



RUNOOB 第 1 次循环

RUNOOB 第 2 次循环

RUNOOB 第 3 次循环

RUNOOB 第 4 次循环

RUNOOB 第 5 次循环

j = 0

j = 1

j = 2

for-in loop (iterating over collections)

for-in is the most concise way to iterate over collections such as List and Set.

Example

void

main

(

)

{

  List

<

String

fruits

=

[

'Apple'

,

'Banana'

,

'Orange'

,

'Grape'

]

;

 

// for-in: take elements from the collection one by one

 

for

(

var

fruit

in

fruits

)

{

    print

(

'RUNOOB fruit: $fruit'

)

;

 

}

}



RUNOOB 水果: 苹果

RUNOOB 水果: 香蕉

RUNOOB 水果: 橙子

RUNOOB 水果: 葡萄

forEach method

List and Set also provide the forEach method, which uses a callback to handle each element.

Example

void

main

(

)

{

  List

<

int

scores

=

[

85

,

92

,

78

,

60

]

;

 

// forEach: execute a callback for each element

  scores.

forEach

(

(

score

)

{

    String result

=

score

=

60

?

'Pass'

:

'Fail'

;

    print

(

'RUNOOB score: $score -> $result'

)

;

 

}

)

;

}



RUNOOB 分数: 85 -> 及格

RUNOOB 分数: 92 -> 及格

RUNOOB 分数: 78 -> 及格

RUNOOB 分数: 60 -> 及格


while and do-while loops

The while loop checks the condition before each iteration, suitable when the number of iterations is uncertain.

Example

void

main

(

)

{

 

// while: check the condition first, then execute

 

int

count

=

3

;

 

while

(

count

0

)

{

    print

(

'RUNOOB countdown: $count'

)

;

    count

--

;

 

// Remember to update the condition variable, otherwise it becomes an infinite loop

 

}

  print

(

'Launch!'

)

;

}



RUNOOB 倒计时: 3

RUNOOB 倒计时: 2

RUNOOB 倒计时: 1

发射!

The difference between do-while and while is that it executes the loop body at least once, because the condition is checked at the end.

Example

void

main

(

)

{

 

// do-while: execute once first, then check the condition

 

int

num

=

0

;

 

do

{

    print

(

'RUNOOB executes at least once, num = $num'

)

;

   

num

++

;

 

}

while

(

num

<

0

)

;

 

// The condition is false from the start

  print

(

'Loop ended, num = $num'

)

;

}



RUNOOB 至少执行一次,num = 0

循环结束,num = 1

do-while guarantees the loop body executes at least once even if the condition is not met from the start. This is useful in try-first-then-judge scenarios, such as reading user input until it is valid.

while vs for: how to choose

Scenario Recommended loop Reason
Number of iterations is fixed for Initialization, condition, and update are written together, clear at a glance
Number of iterations is uncertain while Only focuses on the condition, more flexible
execute at least once do-while Execute first, then judge
Iterate over collections for-in or forEach The most concise way to iterate over collections

break and continue

break immediately exits the entire loop; continue skips the current iteration and moves to the next.

Example

void

main

(

)

{

 

// break: stop the loop immediately once the target is found

  List

<

String

names

=

[

'Alice'

,

'Bob'

,

'runoob'

,

'David'

]

;

 

for

(

var

name

in

names

)

{

    print

(

'Check: $name'

)

;

   

if

(

name

==

'runoob'

)

{

      print

(

'Found RUNOOB!'

)

;

     

break

;

 

// Exit the loop, no longer checking the remaining elements

   

}

 

}

  print

(

'---separator---'

)

;

 

// continue: skip the current iteration

 

for

(

int

i

=

1

;

i

<=

5

;

i

++

)

{

   

if

(

i

==

3

)

{

     

continue

;

 

// Skip the iteration where i=3

   

}

    print

(

'RUNOOB time $i'

)

;

 

}

}



检查: Alice

检查: Bob

检查: runoob

找到 RUNOOB 了!

---分隔线---

RUNOOB 第 1 次

RUNOOB 第 2 次

RUNOOB 第 4 次

RUNOOB 第 5 次

Labeled break and continue

In nested loops, labels let you break out of a specified outer loop.

Example

void

main

(

)

{

 

// The label outerLoop marks the outer loop

  outerLoop

:

 

for

(

int

i

=

1

;

i

<=

3

;

i

++

)

{

   

for

(

int

j

=

1

;

j

<=

3

;

j

++

)

{

      print

(

'i=$i, j=$j'

)

;

     

if

(

i

==

2

&&

j

==

2

)

{

        print

(

'Target found, exiting outer loop'

)

;

       

break

outerLoop

;

 

// Break out of the outer loop labeled outerLoop

     

}

   

}

 

}

  print

(

'Loop ended'

)

;

}



i=1, j=1

i=1, j=2

i=1, j=3

i=2, j=1

i=2, j=2

找到目标,退出外层循环

循环结束

Labels should be used with caution. In most cases, extracting the nested loop logic into a separate function and using return to exit is clearer.