7

Is there a function in Dart which acts as an equivalent to the Goto function, wherein I could transfer the programs control to a specified label.

For example:

var prefs = await SharedPreferences.getInstance();
if (prefs.getString("TimetableCache") == null || refreshing) {
    var response = await http.get(
    Uri.encodeFull("A website",);
    data = JsonDecoder().convert(response.body);
    try {
        if (response != null) {
            prefs.setString("TimetableCache", response.body);
        }
    } catch (Exception) {
        debugPrint(Exception);
    }
   } else {
data = prefs.getString("TimetableCache");
}

if (data != null) {
    try {
       //Cool stuff happens here
    } catch (Exception) {
    prefs.setString("TimetableCache", null);
    }
}

I have an http request and before I want to move on with my 'cool stuff' I have a try catch which sees if anything is in the TimetableCache location of the SharedPreferences of the machine. When it catches the exception I would ideal have a goto method to send it back to the top line again to retry getting the data.

In c# you can use goto refresh;, for example, and the code will then start executing wherever the identifier refresh: is.

Is there a dart version of this?

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
R. Duggan
  • 1,341
  • 2
  • 14
  • 29
  • I wouldn't recommend using a Goto in general. https://stackoverflow.com/questions/46586/goto-still-considered-harmful – George Jan 11 '19 at 20:46

1 Answers1

12

Yes, Dart supports labels. With continue and break you can jump to labels.

https://www.tutorialspoint.com/dart_programming/dart_programming_loops.htm

void main() { 
   outerloop: // This is the label name 

   for (var i = 0; i < 5; i++) { 
      print("Innerloop: ${i}"); 
      innerloop: 

      for (var j = 0; j < 5; j++) { 
         if (j > 3 ) break ; 

         // Quit the innermost loop 
         if (i == 2) break innerloop; 

         // Do the same thing 
         if (i == 4) break outerloop; 

         // Quit the outer loop 
         print("Innerloop: ${j}"); 
      } 
   } 
}

void main() { 
   outerloop: // This is the label name 

   for (var i = 0; i < 3; i++) { 
      print("Outerloop:${i}"); 

      for (var j = 0; j < 5; j++) { 
         if (j == 3){ 
            continue outerloop; 
         } 
         print("Innerloop:${j}"); 
      } 
   } 
}

https://github.com/dart-lang/sdk/issues/30011

switch (x) {
  case 0:
    ...
    continue foo; // s_c
  foo:
  case 1: // s_E (does not enclose s_c)
    ...
    break;
}

See also

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506