Dart中有Goto功能吗?

时间:2019-01-11 19:35:59

标签: 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);
    }
}

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

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

这是飞镖吗?

2 个答案:

答案 0 :(得分:6)

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

另请参见

答案 1 :(得分:1)

否,您将使用while

while (data == null & retries++ < maxRetries) {
  // make an attempt
}
if (data == null) {
  // darn - must have reached max retries :-(
  return;
}
// handle the data