【问题标题】:Calculate Total Sum of a List Dynamically in Flutter Function Issue在 Flutter 函数问题中动态计算列表的总和
【发布时间】:2021-04-12 07:08:00
【问题描述】:

我有这段代码应该计算列表的总和:

int _counter = 0;

Future getTotal(item) async {
int counter = 0;

_totalPrice.add(int.parse(item));
_totalPrice.forEach((element) => counter += element);

print('LIST: $_totalPrice');
print('SUM: $counter');
return counter;

}

_counter应该是全局变量,所以我可以在其他函数中使用它,但是我遇到了这个奇怪的问题,在第二次点击函数后几乎是正方形,这是我点击后的结果两次,而不是添加 1 个 item,SUM 更大:

如您所见,SUM 的结果应该是 312,而不是 468,由于某种原因它计算错误。我只需要它在每次调用函数时正确计算列表的总和。

【问题讨论】:

  • 我同意:使用更实用的样式将帮助您避免“莫名其妙”的错误。但是,您的链接答案不正确,因为它在空列表中失败。请改用fold()。
  • 这样的? sum = given_list.fold(0, (previous, current) => previous + current);

标签: flutter dart


【解决方案1】:

首先你必须将 int 类型转换为字符串,然后将其解析为 int,这是解析可以解析为 int 的 erverthing 的安全方法。 另一个问题是您定义了 _counter 并且您必须在函数中重置它,您错误地再次定义它!

getTotal(item){
_counter = 0;
_totalPrice.add(int.parse(item.toString()));
_totalPrice.forEach((element) => _counter += element);

print('LIST: $_totalPrice');
print('SUM: $_counter');
return _counter;

}

【讨论】:

  • 这是好的答案,但不是我正在寻找的确切答案。问题是回忆 _counter 并没有真正起作用,因为我需要全局的。
  • 你必须在这个函数的最后设置状态才能返回,它会起作用,但最好的方法是使用像GetX这样的全局状态管理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 2011-09-04
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多