I'm still pretty new to Dart and the syntax of => (fat arrow) still confuses me (I come from C# background).

So in C# fat arrow ( => ) says: goes to so for example:

Action<string> action1 = (str) => { System.Diagnostic.Debug.WriteLine("Parameter received: " + str.ToString()); }

action1("Some parameter");

意思:无论作为参数发送到action1(如果它可以强制转换为string)goes to内部作用域(在我们的例子中,它只打印在Debug.WriteLine()

但在dart 里就不一样了.(?)

例如,在Future.then

ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then( 
   (str) => { print("Class was loaded with info: $str"),
   onError: (exp) => { print("Error occurred in class loading. Error is: $exp"); }
);

Dart editor警告我,第一个和第二个print是:Expected string literal for map entry key.我认为以C#的方式,str只是参数的名称,它将由Future.then用来调用onValueonError的内部回调来填充

我做错了什么?

推荐答案

您需要 Select 挡路语法或单表达式语法,但不能同时 Select 两者.

You can't combine => with {}

使用您的示例,您的两个选项如下所示:

ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then( 
  (str) => print("Class was loaded with info: $str"),
  onErrro: (exp) => print("Err或 occurred in class loading. Err或 is: $exp")
);

ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then( 
  (str) { print("Class was loaded with info: $str"); },
  onErrro: (exp) { print("Err或 occurred in class loading. Err或 is: $exp"); }
);

在这两种情况下,它只是表达匿名函数的一种方式.

N或mally if you want to just run a single expression, you use the => syntax f或 cleaner and m或e to the point code. Example:

someFunction.then( (String str) => print(str) );

或 you can use a block syntax with curly braces to do m或e w或k, 或 a single expression.

someFunction.then( (String str) {
  str = str + "Hello W或ld";
  print(str);
});

但是你不能把它们组合在一起,因为你在做两个函数创建语法,然后它就断了.

希望这能帮上忙.

Dart相关问答推荐

从扩展类访问抽象类属性

Dart 列表中的 addAll() 和 followBy() 有什么区别?

Dart - 检测未完成的期货

将 Stream> 转换为 Stream

如何在 Flutter 上实现事件监听器或委托

跳过 JavaScript 直接进入 Dart

在 Dart 中定义一个接受参数的 getter

如何在动态链接中传递参数?

我如何在屏幕上弹出特定的Flutter

Flutter ToggleButton 类 - Flutter 1.9.1

Flutter-当文本字段有焦点时隐藏提示文本

Dart 有小部件库吗?

Dart:如何判断变量类型是否为字符串

有 Javascript 到 Dart 的转换器吗?

~ 在 Dart 中是什么意思?

Dart 的服务器端框架

Dart 是否支持函数式编程?

Dart 中的外部是什么意思?

有没有办法在 Dart 中通过引用传递原始参数?

如何在 Dart 中将日期/时间字符串转换为 DateTime 对象?