flutter - 参数类型“对象?” 不能在颤振中分配给参数类型“num”
问题描述
我是 Flutter 的新手,实际上是在尝试制作一个简单的应用程序。这基本上计算了我的分数。为此,我创建了一个带有 score 属性的问题对象,在这里,当我尝试在问题数组中的特定索引处添加带有分数的总分时,出现错误说参数类型“对象?” 不能分配给参数类型 'num'。我该如何解决这个问题。
class MyAppState extends State<MyApp> {
var questions = [
{
'questionText': 'This is Question 1',
'answers': ['a', 'b'],
'score': 10
},
{
'questionText': 'This is Question 2',
'answers': ['a', 'b'],
'score': 15
},
{
'questionText': 'This is Question 3',
'answers': ['a', 'b'],
'score': 25
},
];
int qindex = 0;
int totalScore = 0;
void answer() {
setState(() {
qindex = qindex + 1;
});
totalScore += questions[qindex]['score']; //<-- here am getting error.
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("App Bar")),
body: qindex <= questions.length - 1
? Column(
children: [
Question(questions[qindex]['questionText']),
...(questions[qindex]['answers'] as List)
.map((ans) => Answer(answer, ans))
],
)
: Center(
child: Text(
"No More Result",
style: TextStyle(fontSize: 28),
),
),
));
}
}
解决方案
您会收到此错误,因为如果密钥不存在questions[qindex]['score']
可以返回,但如果您确定它存在,您可以执行以下操作:null
score
totalScore += questions[qindex]['score'] as int;
推荐阅读
- c++ - 获取从图像相机到另一个图像相机的 3d 点(x,y,深度)坐标
- unity3d - Unity3D + Firebase 邀请,电子邮件有效,短信失败
- reactjs - Typescript Reac + Redux 中的 Union Types 类型错误时属性不存在
- html - 使行尾的箭头保持连接到行中的最后一个单词
- c# - 日期时间对象值为 null 但值仍然抛出 null
- go - 初始化地图问题
- sas - 在 SAS 中创建年龄组变量
- highcharts - pageX,pageY 到 chartX,chartY 的数据点不协调 highcharts
- javascript - 在嵌套 JSON 上使用 dc.js 创建条形图
- kubernetes - Pod 不在本地路径上写入