简化代码以在Flutter中对字段求和

kmbjn2e3  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(138)

我知道这可能是非常基本的,但我无法进一步简化它。我有一个带有Model类“MainDataModel”的sqflite数据库。它有以下字段:“code、startdeg、sweepdeg、levelOne和levelTwo”和12条记录。
每个levelTwo都有两条记录,我试图对字段“sweepdeg”求和(而不是其他字段)。
这段代码运行正常,但显然是不正确的,但主要问题是我必须添加条件(i== 11),因为最后一条记录没有被捕获。
如果代码可以简化,我会很感激。

if (mainData.isNotEmpty) {
     
      String subVarName = mainData[0].subName!;
      double startdeg = mainData[0].startdeg!;
      double sweepdeg = 0;
      for (int i = 0; i < mainData.length; i++) {
       
        if (i == 11) {
          sweepdeg = sweepdeg + mainData[i].sweepdeg!;
          subData.add(MainDataModel(
              code: mainData[i].code,
              startdeg: startdeg,
              sweepdeg: sweepdeg,
              levelOne: mainData[i].levelOne,
              levelTwo: subVarName));
        } else if (subVarName == mainData[i].levelTwo) {
          sweepdeg = sweepdeg + mainData[i].sweepdeg!;
        } else if (subVarName != mainData[i].levelTwo) {
          subData.add(MainDataModel(
              code: mainData[i].code,
              startdeg: startdeg,
              sweepdeg: sweepdeg,
              levelOne: mainData[i].levelOne,
              levelTwo: subVarName));
          sweepdeg = mainData[i].sweepdeg!;
          startdeg = mainData[i].startdeg!;
          subVarName = mainData[i].levelTwo!;
        }
      }
  
    }
j2cgzkjk

j2cgzkjk1#

通过使用groupBymap就可以实现,我也是用集合包来实现的,比如

import 'package:collection/collection.dart';

if (mainData.isNotEmpty) {
  // Group the mainData list by the levelTwo field
  final groups = groupBy(mainData, (MainDataModel data) => data.levelTwo);

  // Map each group to a new list of MainDataModels with the sum of sweepdeg
  final subData = groups.values.map((group) {
    final sweepdegSum = group.fold<double>(0, (sum, data) => sum + data.sweepdeg!);
    return MainDataModel(
      code: group.last.code,
      startdeg: group.first.startdeg,
      sweepdeg: sweepdegSum,
      levelOne: group.last.levelOne,
      levelTwo: group.last.levelTwo,
    );
  }).toList();
}

相关问题