"${element['price'] * element['step']} c"
总是显示错误
The operator '*' isn't defined for the type 'Object'.
结果必须与两个变量相乘并转换为字符串。怎么了?我找不到任何答案。如文档所述进行制作。
element
是var element = {
'title': 'Apple and more more thing',
'category': 'Fruit',
'description': 'Some data to describe',
'price': 24.67,
'bonus': '1% bonus',
'group': 'Picnik',
'step': 1.0
};
最佳答案
Dart是一种静态类型安全语言,因此在您的代码甚至没有运行之前,就已经对代码进行了分析,以确保没有静态确定的类型问题。
在您的示例中,您已经定义了以下变量:
var element = {
'title': 'Apple and more more thing',
'category': 'Fruit',
'description': 'Some data to describe',
'price': 24.67,
'bonus': '1% bonus',
'group': 'Picnik',
'step': 1.0
};
通过使用var
,您正在告诉Dart它应该自动确定类型。在这种情况下也可以这样做。 Dart将看到 map 中的所有键都是String
,因此我们可以放心地假设键类型为String
。然后,它查看值并尝试查找所有值都通用的类型。因为我们同时拥有
double
和String
作为值,所以类型必须是Object
,因为如果我们想要包含所有值的类型,我们就不能更具体。因此, map 的类型将确定为:
Map<String, Object>
。然后,当您在 map 上使用
[]
运算符时,将定义为从该 map 返回Object
,因为这是我们唯一可以确定的事情。但这是您尝试执行的问题:
"${element['price'] * element['step']} c"
由于我们在分析器阶段可以看到我们将在*
上调用Object
运算符,因此,分析器将因类型错误而停止程序,因为您尝试执行的操作被视为类型安全。有多种修复方法,您也可以在其他答案中看到:
类型转换
您可以告诉Dart“嘿,我知道我在做什么”,并强制Dart使用以下特定类型:
"${(element['price'] as double) * (element['step'] as double)} c"
动态您可以声明 map 包含
dynamic
作为值:var element = <String, dynamic>{
'title': 'Apple and more more thing',
'category': 'Fruit',
'description': 'Some data to describe',
'price': 24.67,
'bonus': '1% bonus',
'group': 'Picnik',
'step': 1.0
};
这将删除映射中值的所有类型安全性,然后您可以对映射中的值进行任何所需的操作,而不必担心分析器的类型问题。但是,然后将在运行时检查类型,如果您输入的类型错误(如类型转换),可能会使您的应用程序崩溃。类解决方案
您确实不应该像现在那样使用
Map
。而是创建一个类:void main() {
var element = Element(
title: 'Apple and more more thing',
category: 'Fruit',
description: 'Some data to describe',
price: 24.67,
bonus: '1% bonus',
group: 'Picnik',
step: 1.0);
print("${element.price * element.step} c"); // 24.67 c
}
class Element {
String title;
String category;
String description;
double price;
String bonus;
String group;
double step;
Element(
{this.title,
this.category,
this.description,
this.price,
this.bonus,
this.group,
this.step});
}
这样,您可以确保Dart知道每个属性的类型并获得类型安全性。
关于string - 如何在Dart的字符串中乘以两个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63115319/