Dart中有Goto功能吗?

R. *_*gan 4 dart flutter

Dart中有一个函数等效于Goto函数,在其中我可以将程序控件转移到指定标签。

例如:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个http请求,在继续“酷炫的东西”之前,我有一个try catch,它可以查看机器的TimetableCache位置是否有东西SharedPreferences。当它捕获到异常时,我希望有一个goto方法将其再次发送回第一行以重试获取数据。

goto refresh;例如,在c#中,您可以使用,然后无论标识符refresh:位于何处,代码都将开始执行。

有飞镖版本吗?

Gün*_*uer 8

是的,Dart支持标签。使用continuebreak可以跳到标签。

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}"); 
      } 
   } 
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

也可以看看