8

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
  • 623,577
  • 216
  • 2,003
  • 1,567
RhysD
  • 1,597
  • 2
  • 17
  • 30
  • 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

15

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++) { 
         // Quit the innermost loop 
         if (j > 3 ) break ; 
         
         // Do the same thing 
         if (i == 2) break innerloop; 
         
         // Quit the outer loop 
         if (i == 4) break outerloop; 
         
         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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567