avatarConstantin Stan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4127

Abstract

ring-dart-9a3e74b0d9c5">Enumerated types</a> fit like a glove when used with <b>switch</b> statements:</p><div id="80e5"><pre><span class="hljs-attribute">enum CatMoods</span> = {meowing, sleepy, playful, curious, angry};</pre></div><div id="fe32"><pre><span class="hljs-keyword">switch</span>(myCat.mood) { <span class="hljs-keyword">case</span> meowing: feed(myCat); <span class="hljs-keyword">break</span>; catAngerManagement:
<span class="hljs-keyword">case</span> playful: <span class="hljs-keyword">case</span> curious: pet(myCat); <span class="hljs-keyword">break</span>; <span class="hljs-keyword">case</span> angry: <span class="hljs-keyword">continue</span> catAngerManagement <span class="hljs-keyword">case</span> sleepy: <span class="hljs-keyword">continue</span>; <span class="hljs-keyword">default</span>: takePictures(myCat); }</pre></div><p id="f149">Using <b>enum</b>s in <b>switch</b> statements forces you to handle all possible cases.</p><p id="1562">A non-empty <b>case</b> clause usually ends with a <b>break</b> statement. It can also end with <b>continue</b>, <b>throw</b>, or <b>return</b>. Not ending such clause will generate an error.</p><p id="3ef5">As we can see in the example above, Dart also supports empty case clauses (<code>case playful:</code>). There is also an interesting <b>continue</b> to custom label (<code>catAngerManagement</code>).</p><p id="5941">Any local variable declared inside a <b>case</b> statement is visible only in the scope of that clause.</p><p id="7548">Notice that the <b>switch</b> statements are not as flexible as we’d expect and that is because they are<b> intended for limited circumstances</b>, such as in interpreters or scanners.</p><h2 id="7182">Loop statements</h2><p id="daf2">Loops allow us to run a block of code multiple times. Doing so, we reuse code.</p><p id="bdd5">Running a dedicated amount of times is possible using the <b>for</b> loop:</p><div id="3fb8"><pre><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:math'</span>;</pre></div><div id="d803"><pre><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">weirdMeow</span>()</span> {</pre></div><div id="30c3"><pre> <span class="hljs-keyword">var</span> meow = <span class="hljs-built_in">StringBuffer</span>(<span class="hljs-string">'M'</span>);</pre></div><div id="fd32"><pre> <span class="hljs-keyword">var</span> random = Random.secure();

<span class="hljs-built_in">List</span><<span class="hljs-built_in">String</span>> meows = <<span class="hljs-built_in">String</span>>[<span class="hljs-string">'m'</span>,<span class="hljs-string">'e'</span>,<span class="hljs-string">'o'</span>, <span class="hljs-string">'w'</span>];

meows.forEach((<span class="hljs-built_in">String</span> m) { <span class="hljs-built_in">int</span> l = <span class="hljs-number">1</span> + random.nextInt(<span class="hljs-number">5</span>); <span class="hljs-keyword">for</span> (<span class="hljs-built_in">int</span> i = <span class="hljs-number">0</span>; i < l; i++) { meow.write(m); } }); <span class="hljs-built_in">print</span>(<span class="hljs-string">'<span class="hljs-subst">$meow</span>!'</span>); <span class="hljs-comment">// prints something like:</span> <span class="hljs-comment">// Mmmmmeeeeeoooooww!</span></pre></div><div id="4331"><pre>}</pre></div><p id="fafa">Above, we’ve defined the <b>weirdMeow</b> function that will produce, each time, a different <b>meow</b>. For that we use a random generator and two flavors of the <b>for</b> loop: <b>for</b> and <b>forEach</b>.</p><p id="e340">The latter is available for an <b>Iterable</b> object. Using <b>forEach()</b> is useful when we don’t need to know the iteration counter.</p><p id="d048"><b>Iterable</b> objects also support the third flavor of the <b>for</b> loop, <b>for</b><b>in</b>. The above <b>forEach</b> example becomes:</p><div id="a379"><pre><span class="hljs-comment">// ...</span> <span class="hljs-keyword">for</span>(<span class="hljs-type">String</span>

Options

m in meows) { <span class="hljs-type">int</span> l = <span class="hljs-number">1</span> + random.<span class="hljs-built_in">nextInt</span>(<span class="hljs-number">5</span>); <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i < l; i++) { meow.<span class="hljs-built_in">write</span>(m); } } <span class="hljs-comment">// ...</span></pre></div><p id="8018">Multiple iterations are also possible using the <b>while</b> loop. There are two flavors of that:</p><ul><li>simple <b>while</b> loop - that evaluates the condition before the loop, and runs zero to any number of times it takes for the condition to be met</li><li>and a <b>do</b><b>while</b> loop - which evaluates the condition after the loop, running at least once</li></ul><div id="61b2"><pre><span class="hljs-comment">// simple while</span> <span class="hljs-built_in">while</span>(isTooDark()) { <span class="hljs-built_in">bringUpTheLevelOfLightBy</span>(<span class="hljs-number">10</span>); }</pre></div><div id="93fd"><pre><span class="hljs-regexp">//</span> <span class="hljs-keyword">do</span>-<span class="hljs-keyword">while</span> <span class="hljs-keyword">do</span> { bringUpTheLevelOfLightBy(<span class="hljs-number">10</span>); } <span class="hljs-keyword">while</span>(isTooDark());</pre></div><p id="aacd">The simple <b>while</b> will bring up the level of light only if its too dark, compared to the <b>do</b><b>while</b>, which will will bring up the level of light at least by 10, no matter what.</p><p id="b4ee"><b>Break</b> and <b>continue</b> are used to stop looping, or respectively, skip to the next loop iteration.</p><div id="f6c3"><pre><span class="hljs-tag"><<span class="hljs-name">Cat</span>></span>List cats = <span class="hljs-tag"><<span class="hljs-name">Cat</span>></span>[simba, micuta, klein, saki];</pre></div><div id="57be"><pre><span class="hljs-built_in">for</span>(Cat currentCat in cats) { <span class="hljs-built_in">if</span>(!currentCat.isHungry) { continue; } <span class="hljs-built_in">feed</span>(currentCat); }</pre></div><p id="d928">In the previous example, we’ll iterate through our cats and feed only the ones that are hungry. The others, we skip.</p><p id="fdca">During development we can use the <b>assert</b> statement with the following syntax:</p><div id="8047"><pre><span class="hljs-built_in">assert</span>(condition, optionalMessage);</pre></div><p id="3e6c">We’ve already used it many times in our <a href="https://medium.com/tag/fluttering-dart/archive">Fluttering Dart</a> journey for disrupting normal execution if the boolean condition is false.</p><p id="8046">If the expression’s value is true, the assertion succeeds and execution continues. If it’s false, the assertion fails and an exception.</p><p id="8203">Flutter enables assertions in debug mode, while tools such as <a href="https://dart.dev/tools/dart2js"><b>dart2js</b></a> (used to build for the web platform) support assertions through a command-line flag <code>--enable-asserts</code>.</p><p id="81a2">In production code, assertions are ignored, and the arguments to <code>assert</code> aren’t evaluated</p><p id="147e">In the next part of the <a href="https://medium.com/tag/fluttering-dart/archive"><b>Fluttering Dart</b></a> series, we’ll delve into <a href="https://readmedium.com/fluttering-dart-oop-8b92cd89a7f0">classes, objects and other object-orientated programming</a> aspects of Dart.</p><div id="b326" class="link-block"> <a href="https://readmedium.com/fluttering-dart-oop-8b92cd89a7f0"> <div> <div> <h2>Fluttering Dart: OOP</h2> <div><h3>Classes, Objects, Interfaces, and a lot more</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*HqqArYF_xyAaZtyGWfDtkw.png)"></div> </div> </div> </a> </div><p id="f25e">Tha(nk|t’)s all!</p></article></body>

Fluttering Dart

Fluttering Dart: The Flow

All about the control flow statements

Photo by Blake Richard Verdoorn on Unsplash

Flutter projects can use both platform-specific and cross-platform code. The latter is written in Dart, and, for building Flutter apps, some basic knowledge of Dart is required.

Fluttering Dart’s goal is to explore fundamental knowledge and unveil tips & tricks of the powerful programming language that brings Flutter to life.

In the previous parts of the series, we went through the Dart built-in data types, functions and operators.

In this part, we’ll discover how to write and use control flow statements.

Some of the code examples can be tried out, and played with, using DartPad.

Control flow statements

If you're coming from another imperative programming language, you'll be familiar with control flow statements available in Dart.

There are the conditional statements: ifelse and switchcase, and the iterative statements: for, for in, forEach, while and dowhile loops. There are also some ”helper” statements: break, continue and assert. Don’t forget that we’ve also discussed the trycatch and throw statements a while back when we talked about functions.

Conditional statements

These are used to decide actions (more specific the execution of code) based on meeting/matching certain boolean conditions.

Dart supports if statements with optional else elements:

if(myCat.meowing) {
  feed(myCat);
} else if(!myCat.sleepy) {
  pet(myCat);
} else {
  // don't disturb the cat
  takePicturesOf(myCat);
}

If you remember the conditional operator, it’s pretty much a shorthand notation of an ifelse statement ( condition ? expr1 : expr2 ).

A one liner of the above example is:

myCat.meowing ? feed(myCat) : ( !myCat.sleepy ? pet(myCat) : takePicturesOf(myCat) );

We should not code this way because is way less readable.

Conditions must use only boolean values (bool typed objects or expressions that evaluation returns bool).

Switch statements can compare integer, string or compile-time constants, using ==. Compared objects must be all of the same class, with no overriding of the == operator. Enumerated types fit like a glove when used with switch statements:

enum CatMoods = {meowing, sleepy, playful, curious, angry};
switch(myCat.mood) {
  case meowing:
    feed(myCat);
    break;
  catAngerManagement:  
  case playful:
  case curious:
    pet(myCat);
    break;
  case angry:
    continue catAngerManagement
  case sleepy:
    continue;
  default:
    takePictures(myCat);
}

Using enums in switch statements forces you to handle all possible cases.

A non-empty case clause usually ends with a break statement. It can also end with continue, throw, or return. Not ending such clause will generate an error.

As we can see in the example above, Dart also supports empty case clauses (case playful:). There is also an interesting continue to custom label (catAngerManagement).

Any local variable declared inside a case statement is visible only in the scope of that clause.

Notice that the switch statements are not as flexible as we’d expect and that is because they are intended for limited circumstances, such as in interpreters or scanners.

Loop statements

Loops allow us to run a block of code multiple times. Doing so, we reuse code.

Running a dedicated amount of times is possible using the for loop:

import 'dart:math';
void weirdMeow() {
  var meow = StringBuffer('M');
  var random = Random.secure();
  
  List<String> meows = <String>['m','e','o', 'w'];
  
  meows.forEach((String m) {
    int l = 1 + random.nextInt(5);
    for (int i = 0; i < l; i++) {
      meow.write(m);
    }
  });
  print('$meow!');
  // prints something like:
  // Mmmmmeeeeeoooooww!
}

Above, we’ve defined the weirdMeow function that will produce, each time, a different meow. For that we use a random generator and two flavors of the for loop: for and forEach.

The latter is available for an Iterable object. Using forEach() is useful when we don’t need to know the iteration counter.

Iterable objects also support the third flavor of the for loop, forin. The above forEach example becomes:

// ...
for(String m in meows) {
  int l = 1 + random.nextInt(5);
  for(int i = 0; i < l; i++) {
    meow.write(m);
  }
}
// ...

Multiple iterations are also possible using the while loop. There are two flavors of that:

  • simple while loop - that evaluates the condition before the loop, and runs zero to any number of times it takes for the condition to be met
  • and a dowhile loop - which evaluates the condition after the loop, running at least once
// simple while
while(isTooDark()) {
  bringUpTheLevelOfLightBy(10); 
}
// do-while
do {
   bringUpTheLevelOfLightBy(10);
} while(isTooDark());

The simple while will bring up the level of light only if its too dark, compared to the dowhile, which will will bring up the level of light at least by 10, no matter what.

Break and continue are used to stop looping, or respectively, skip to the next loop iteration.

<Cat>List cats = <Cat>[simba, micuta, klein, saki];
for(Cat currentCat in cats) {
  if(!currentCat.isHungry) {
    continue;
  }
  feed(currentCat);
}

In the previous example, we’ll iterate through our cats and feed only the ones that are hungry. The others, we skip.

During development we can use the assert statement with the following syntax:

assert(condition, optionalMessage);

We’ve already used it many times in our Fluttering Dart journey for disrupting normal execution if the boolean condition is false.

If the expression’s value is true, the assertion succeeds and execution continues. If it’s false, the assertion fails and an exception.

Flutter enables assertions in debug mode, while tools such as dart2js (used to build for the web platform) support assertions through a command-line flag --enable-asserts.

In production code, assertions are ignored, and the arguments to assert aren’t evaluated

In the next part of the Fluttering Dart series, we’ll delve into classes, objects and other object-orientated programming aspects of Dart.

Tha(nk|t’)s all!

Programming
Dart
Flutter
Fluttering Dart
Coding
Recommended from ReadMedium