首页 > 解决方案 > Dart 中有 Goto 函数吗?

问题描述

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);
    }
}

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

例如,在 c# 中,您可以使用goto refresh;,然后代码将在标识符refresh:所在的任何位置开始执行。

这个有飞镖版本吗?

标签: dartflutter

解决方案


是的,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}"); 
      } 
   } 
}

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;
}

也可以看看


推荐阅读