DART: Passing function in a function as parameter

此生再无相见时 提交于 2021-01-29 08:57:08

问题


The below snippet of code gives me error in dartpad. But the same code works fine in the course which I am doing online. I am using dart version 2.8.4.

void main() {
  
 int var = operation(5,5,add);  --> Error
  
  //print(operation(5,5,add));
}

// class calculator {
  
//   calculator({this.operand});
  
// }
  

int add(int n1, int n2) {
  return n1+n2;
}

int multiply(int n1, int n2) {
  return n1*n2;
}

int operation(int n1, int n2, Function operand){
  return operand(n1, n2);
}

Error:

Error compiling to JavaScript:
main.dart:3:2:
Error: Expected ';' after this.
 int var = operation(5,5,add);
 ^^^
main.dart:3:10:
Error: Expected an identifier, but got '='.
 int var = operation(5,5,add);
         ^
Error: Compilation failed.

回答1:


int var = operation(5,5,add); don't use var as a variable name, it a keyword used in the dartlang, just change the name to anything else and you wont get any error:

int operationResult = operation(5,5,add);


来源:https://stackoverflow.com/questions/62550421/dart-passing-function-in-a-function-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!