Суммируйте список целых чисел внутри дротика со списком - PullRequest
0 голосов
/ 04 августа 2020

У меня небольшая проблема. У меня есть класс model со списком. Внутри списка есть еще один список, в котором мне нужно реализовать суммирование целых чисел. Я продолжаю получать эту ошибку диапазона из моего кода дротика, когда он реализован с помощью for l oop. Какой самый чистый способ добиться этого суммирования?

Main.dart

 int totalSpendAmount = 0;
  int totalSpendQuantity = 0;
  List<int> spendList = [];
  List<int> quantityList = [];
@override
  Widget build(BuildContext context) {
    return ListView.builder(
        shrinkWrap: true,
        physics: ScrollPhysics(),
        itemCount: widget.materials != null ? widget.materials.length : 0,
        itemBuilder: (BuildContext context, int index) {
          amountPlan = FlutterMoneyFormatter(
                  amount: (widget.materials[index].budget.toDouble()))
              .output;
          //for loop to calculate all purchases for amount and quantity spent
          for (var i = 0; i < widget.materials.length; i++) {
            if(widget.materials[index].purchase!=null){
           widget.materials.forEach((e) => totalSpendAmount += e.purchase[index].amount);
            }
            spendList.add(totalSpendAmount);
          }
         

Класс модели

class Materials {
  String id;
  String title;
  String brand;
  String measurementUnit;
  int proposedQuantity;
  int budget;
  int quantityInStore;
  int quantityUsed;
  int unitCost;
  bool approved;
  String createdAt;
  String updatedAt;
  String taskId;
  List<Purchase> purchase;

  Materials(
      {this.id,
        this.title,
        this.brand,
        this.measurementUnit,
        this.proposedQuantity,
        this.budget,
        this.quantityInStore,
        this.quantityUsed,
        this.unitCost,
        this.approved,
        this.createdAt,
        this.updatedAt,
        this.taskId,
        this.purchase});
  static List<Materials> fromJsonList(List<dynamic> _list) {
    return _list.map((_tasks) => Materials.fromJson(_tasks)).toList();
  }

}

class Purchase {
  String id;
  int quantity;
  int amount;
  int discount;
  String receipt;
  String materialId;
  String projectId;
  String createdAt;
  String updatedAt;
  String purchasedBy;

  Purchase(
      {this.id,
        this.quantity,
        this.amount,
        this.discount,
        this.receipt,
        this.materialId,
        this.projectId,
        this.createdAt,
        this.updatedAt,
        this.purchasedBy});
  }

Мне нужен список всего суммирования целого числа amount внутри объекта Purchase для индексов материалов, которые будут переданы внутри моего ListView.Builder's виджета

1 Ответ

0 голосов
/ 04 августа 2020

Вы можете добиться этого, используя метод fold. Вы можете проверить эту документацию https://api.dart.dev/stable/1.10.1/dart-core/List/fold.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...