在Flutter中,基于日期在DataRow中显示子总计的代码部分可能如下所示:

huangapple go评论84阅读模式
英文:

Displaying Sub Totals based on Dates in DataRow of DataTable using Flutter

问题

我想实现如下的 DataTable,它在每个唯一日期后显示小计,包含对象数组。

以下是我用于根据唯一日期对数组进行排序的代码:

class _DateWiseReportState extends State<DateWiseReport> {
  List<Map> _reports = [
    {
      'scan_date': '01.07.23',
      'engine_type': '2S',
      'coupon_value': 5,
      'quantity': 3,
      'amount': 15,
    },
    {
      'scan_date': '01.07.23',
      'engine_type': '4S',
      'coupon_value': 10,
      'quantity': 2,
      'amount': 20,
    },
    {
      'scan_date': '01.07.23',
      'engine_type': '3W',
      'coupon_value': 10,
      'quantity': 2,
      'amount': 20,
    },
    {
      'scan_date': '02.07.23',
      'engine_type': '2S',
      'coupon_value': 5,
      'quantity': 2,
      'amount': 10,
    },
    {
      'scan_date': '02.07.23',
      'engine_type': '4S',
      'coupon_value': 10,
      'quantity': 3,
      'amount': 30,
    },
    {
      'scan_date': '01.07.23',
      'engine_type': '3W',
      'coupon_value': 10,
      'quantity': 3,
      'amount': 30,
    }
  ];

  // 在这里添加计算小计的代码

  _reports.sort((a, b) {
    return a['scan_date'].compareTo(b['scan_date']!);
  });

  // 在这里添加创建列的代码

  // 在这里添加创建行的代码
}

请添加计算小计、创建列和创建行的代码,以实现所需的输出效果。

英文:

I want to achieve the DataTable like below that displays sub totals after each unique dates having array of objects

Below is the code which I used to sort the array based on unique dates

    class _DateWiseReportState extends State&lt;DateWiseReport&gt; {
  List&lt;Map&gt; _reports = [
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;2S&#39;,
      &#39;coupon_value&#39;: 5,
      &#39;quantity&#39;: 3,
      &#39;amount&#39;: 15,
    },
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;4S&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 2,
      &#39;amount&#39;: 20,
    },
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;3W&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 2,
      &#39;amount&#39;: 20,
    },
    {
      &#39;scan_date&#39;: &#39;02.07.23&#39;,
      &#39;engine_type&#39;: &#39;2S&#39;,
      &#39;coupon_value&#39;: 5,
      &#39;quantity&#39;: 2,
      &#39;amount&#39;: 10,
    },
    {
      &#39;scan_date&#39;: &#39;02.07.23&#39;,
      &#39;engine_type&#39;: &#39;4S&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 3,
      &#39;amount&#39;: 30,
    },
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;3W&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 3,
      &#39;amount&#39;: 30,
    }
  ];

  for (var reportData in _reports) {
       int quantity = reportData[&#39;quantity&#39;];
       int amount = reportData[&#39;amount&#39;];
       int couponValue = reportData[&#39;coupon_value&#39;];

       totalQuantity += quantity.toInt();
       totalAmount += amount.toInt();
       totalCouponValue += couponValue.toInt();
  }

  _reports.sort((a, b) {
      return a[&#39;scan_date&#39;].compareTo(b[&#39;scan_date&#39;]!);
  });

List&lt;DataColumn&gt; _createColumns() {
    return [
      DataColumn(
          label: Expanded(
              child: Text(
        &#39;Scan Date&#39;,
        textAlign: TextAlign.center,
      ))),
      DataColumn(
          label: Text(
        &#39;E-Type&#39;,
        textAlign: TextAlign.center,
      )),
      DataColumn(
          label: Expanded(
              child: Text(
        &#39;Value&#39;,
        textAlign: TextAlign.center,
      ))),
      DataColumn(
          label: Expanded(
              child: Text(
        &#39;QTY&#39;,
        textAlign: TextAlign.center,
      ))),
      DataColumn(
        label: Expanded(
            child: Text(
          &#39;Amount(Rs)&#39;,
          textAlign: TextAlign.center,
        )),
        onSort: (columnIndex, _) {
          setState(() {
            _currentSortColumn = columnIndex;
            if (_isSortAsc) {
              _reports.sort((a, b) =&gt; b[&#39;amount&#39;].compareTo(a[&#39;amount&#39;]));
            } else {
              _reports.sort((a, b) =&gt; a[&#39;amount&#39;].compareTo(b[&#39;amount&#39;]));
            }
            _isSortAsc = !_isSortAsc;
          });
        },
      ),
    ];
  }

  List&lt;DataRow&gt; _createRows() {
    return _reports
        .map((report) =&gt; DataRow(cells: [
              DataCell(
                  Text(
                    report[&#39;scan_date&#39;].toString(),
                    textAlign: TextAlign.center,
                  ), onTap: () {
                print(&quot;Clicked row at scan_date&quot;);
              }),
              DataCell(
                  Text(
                    report[&#39;engine_type&#39;].toString(),
                    textAlign: TextAlign.center,
                  ), onTap: () {
                print(&quot;Clicked row at engine_type&quot;);
              }),
              DataCell(
                  Text(
                    report[&#39;coupon_value&#39;].toString(),
                    textAlign: TextAlign.center,
                  ), onTap: () {
                print(&quot;Clicked row at coupon_value&quot;);
              }),
              DataCell(
                  Text(
                    report[&#39;quantity&#39;].toString(),
                    textAlign: TextAlign.center,
                  ), onTap: () {
                print(&quot;Clicked row at quantity&quot;);
              }),
              DataCell(
                  Text(
                    report[&#39;amount&#39;].toString(),
                    textAlign: TextAlign.center,
                  ), onTap: () {
                print(&quot;Clicked row at amount&quot;);
              })
            ]))
        .toList();
  }

在Flutter中,基于日期在DataRow中显示子总计的代码部分可能如下所示:

在Flutter中,基于日期在DataRow中显示子总计的代码部分可能如下所示:

Can anyone suggest how we can achieve the sub totals based on after unique dates.

答案1

得分: 2

以下是您要翻译的代码部分:

List&lt;DataRow&gt; _createRows() {
    List&lt;DataRow&gt; rows = [];
    int currentSubtotalAmount = 0;

    // Flag for first iteration otherwise it will add subtotal row at the beginning
    bool isFirstIteration = true;

    _reports.sort((a, b) {
      final aDate = a[&#39;scan_date&#39;] as String;
      final bDate = b[&#39;scan_date&#39;] as String;
      return aDate.compareTo(bDate);
    });

    for (var report in _reports) {
      final reportDate = report[&#39;scan_date&#39;] as String;

      if (reportDate != currentDate) {
        // Add a subtotal row for the previous date group
        if (currentDate.isNotEmpty &amp;&amp; currentSubtotalAmount &gt; 0) {
          rows.add(_createSubtotalRow(currentSubtotalAmount));
          currentSubtotalAmount = 0;
        }

        currentDate = reportDate;

        // Only add date row if it&#39;s not the first iteration
        if (!isFirstIteration) {
          rows.add(_createDateRow(currentDate));
        }
      }

      rows.add(_createReportRow(report));

      currentSubtotalAmount += report[&#39;amount&#39;] as int;

      // After first iteration, set the flag to false
      if (isFirstIteration) {
        isFirstIteration = false;
      }
    }

    // Add a final subtotal row
    rows.add(_createSubtotalRow(currentSubtotalAmount));

    return rows;
}

如果您需要翻译其他部分,请告诉我。

英文:

Result

在Flutter中,基于日期在DataRow中显示子总计的代码部分可能如下所示:

Explanation

I've refactored your code and created a _createRows function where the main logic is:

   List&lt;DataRow&gt; _createRows() {
    List&lt;DataRow&gt; rows = [];
    int currentSubtotalAmount = 0;

    // Flag for first iteration otherwise it will add subtotal row at the beginning
    bool isFirstIteration = true;

    _reports.sort((a, b) {
      final aDate = a[&#39;scan_date&#39;] as String;
      final bDate = b[&#39;scan_date&#39;] as String;
      return aDate.compareTo(bDate);
    });

    for (var report in _reports) {
      final reportDate = report[&#39;scan_date&#39;] as String;

      if (reportDate != currentDate) {
        // Add a subtotal row for the previous date group
        if (currentDate.isNotEmpty &amp;&amp; currentSubtotalAmount &gt; 0) {
          rows.add(_createSubtotalRow(currentSubtotalAmount));
          currentSubtotalAmount = 0;
        }

        currentDate = reportDate;

        // Only add date row if it&#39;s not the first iteration
        if (!isFirstIteration) {
          rows.add(_createDateRow(currentDate));
        }
      }

      rows.add(_createReportRow(report));

      currentSubtotalAmount += report[&#39;amount&#39;] as int;

      // After first iteration, set the flag to false
      if (isFirstIteration) {
        isFirstIteration = false;
      }
    }

    // Add a final subtotal row
    rows.add(_createSubtotalRow(currentSubtotalAmount));

    return rows;
  }

The loop iterates through each report in the _reports list:

If the current report's &#39;scan_date&#39; is different from the currentDate, it means a new date group has started. And in that case:

  • If currentDate is not empty (Meaning, not the first date
    encountered), it adds a subtotal row for the previous date
    group using _createSubtotalRow(currentSubtotalAmount).

  • It resets currentSubtotalAmount to 0 because a new date group has started

Code

import &#39;package:flutter/material.dart&#39;;

void main() async {
  runApp(ExampleWidget());
}

class ExampleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DateWiseReport(),
    );
  }
}

class DateWiseReport extends StatefulWidget {
  const DateWiseReport({Key? key}) : super(key: key);

  @override
  State&lt;DateWiseReport&gt; createState() =&gt; _DateWiseReportState();
}

class _DateWiseReportState extends State&lt;DateWiseReport&gt; {
  final _reports = [
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;2S&#39;,
      &#39;coupon_value&#39;: 5,
      &#39;quantity&#39;: 3,
      &#39;amount&#39;: 15,
    },
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;4S&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 2,
      &#39;amount&#39;: 20,
    },
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;3W&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 2,
      &#39;amount&#39;: 20,
    },
    {
      &#39;scan_date&#39;: &#39;02.07.23&#39;,
      &#39;engine_type&#39;: &#39;2S&#39;,
      &#39;coupon_value&#39;: 5,
      &#39;quantity&#39;: 2,
      &#39;amount&#39;: 10,
    },
    {
      &#39;scan_date&#39;: &#39;02.07.23&#39;,
      &#39;engine_type&#39;: &#39;4S&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 3,
      &#39;amount&#39;: 30,
    },
    {
      &#39;scan_date&#39;: &#39;01.07.23&#39;,
      &#39;engine_type&#39;: &#39;3W&#39;,
      &#39;coupon_value&#39;: 10,
      &#39;quantity&#39;: 3,
      &#39;amount&#39;: 30,
    }
  ];

  
  late String currentDate = _reports[0][&#39;scan_date&#39;] as String;

  void _sortReportsByAmount() {
    _reports.sort((a, b) {
      final aAmount = a[&#39;amount&#39;] as int;
      final bAmount = b[&#39;amount&#39;] as int;
      return aAmount.compareTo(bAmount);
    });
  }

  List&lt;DataColumn&gt; _createColumns() {
    return [
      DataColumn(label: Text(&#39;Scan Date&#39;, textAlign: TextAlign.center)),
      DataColumn(label: Text(&#39;E-Type&#39;, textAlign: TextAlign.center)),
      DataColumn(label: Text(&#39;Value&#39;, textAlign: TextAlign.center)),
      DataColumn(label: Text(&#39;QTY&#39;, textAlign: TextAlign.center)),
      DataColumn(
        label: Text(&#39;Amount(Rs)&#39;, textAlign: TextAlign.center),
        onSort: (columnIndex, _) {
          setState(() {
            _sortReportsByAmount();
          });
        },
      ),
    ];
  }

  List&lt;DataRow&gt; _createRows() {
    List&lt;DataRow&gt; rows = [];
    int currentSubtotalAmount = 0;

    // Flag for first iteration otherwise it will add subtotal row at the beginning
    bool isFirstIteration = true;

    _reports.sort((a, b) {
      final aDate = a[&#39;scan_date&#39;] as String;
      final bDate = b[&#39;scan_date&#39;] as String;
      return aDate.compareTo(bDate);
    });

    for (var report in _reports) {
      final reportDate = report[&#39;scan_date&#39;] as String;

      if (reportDate != currentDate) {
        // Add a subtotal row for the previous date group
        if (currentDate.isNotEmpty &amp;&amp; currentSubtotalAmount &gt; 0) {
          rows.add(_createSubtotalRow(currentSubtotalAmount));
          currentSubtotalAmount = 0;
        }

        currentDate = reportDate;

        // Only add date row if it&#39;s not the first iteration
        if (!isFirstIteration) {
          rows.add(_createDateRow(currentDate));
        }
      }

      rows.add(_createReportRow(report));

      currentSubtotalAmount += report[&#39;amount&#39;] as int;

      // After first iteration, set the flag to false
      if (isFirstIteration) {
        isFirstIteration = false;
      }
    }

    // Add a final subtotal row
    rows.add(_createSubtotalRow(currentSubtotalAmount));

    return rows;
  }

  DataRow _createDateRow(String date) {
    return DataRow(cells: [
      DataCell(Text(date, textAlign: TextAlign.center)),
      DataCell(Text(&#39;&#39;), // Empty cell for E-Type
          onTap: () {
        print(&quot;Clicked date cell&quot;);
      }),
      DataCell(Text(&#39;&#39;), // Empty cell for Value
          onTap: () {
        print(&quot;Clicked date cell&quot;);
      }),
      DataCell(Text(&#39;&#39;), // Empty cell for QTY
          onTap: () {
        print(&quot;Clicked date cell&quot;);
      }),
      DataCell(Text(&#39;&#39;), // Empty cell for Amount
          onTap: () {
        print(&quot;Clicked date cell&quot;);
      }),
    ]);
  }

  DataRow _createReportRow(Map&lt;String, dynamic&gt; report) {
    return DataRow(cells: [
      DataCell(
          Text(report[&#39;scan_date&#39;].toString(), textAlign: TextAlign.center),
          onTap: () {
        print(&quot;Clicked row at scan_date&quot;);
      }),
      DataCell(
          Text(report[&#39;engine_type&#39;].toString(), textAlign: TextAlign.center),
          onTap: () {
        print(&quot;Clicked row at engine_type&quot;);
      }),
      DataCell(
          Text(report[&#39;coupon_value&#39;].toString(), textAlign: TextAlign.center),
          onTap: () {
        print(&quot;Clicked row at coupon_value&quot;);
      }),
      DataCell(Text(report[&#39;quantity&#39;].toString(), textAlign: TextAlign.center),
          onTap: () {
        print(&quot;Clicked row at quantity&quot;);
      }),
      DataCell(Text(report[&#39;amount&#39;].toString(), textAlign: TextAlign.center),
          onTap: () {
        print(&quot;Clicked row at amount&quot;);
      }),
    ]);
  }

  DataRow _createSubtotalRow(int subtotalAmount) {
    return DataRow(
      cells: [
        DataCell(Text(
          &#39;Subtotal&#39;,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        )),
        DataCell(Text(&#39;&#39;), // Empty cell for E-Type
            onTap: () {
          print(&quot;Clicked subtotal cell&quot;);
        }),
        DataCell(Text(&#39;&#39;), // Empty cell for Value
            onTap: () {
          print(&quot;Clicked subtotal cell&quot;);
        }),
        DataCell(Text(&#39;&#39;), // Empty cell for QTY
            onTap: () {
          print(&quot;Clicked subtotal cell&quot;);
        }),
        DataCell(
            Text(subtotalAmount.toString(),
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            onTap: () {
          print(&quot;Clicked subtotal cell&quot;);
        }),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(&#39;Date Wise Report&#39;),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: DataTable(
          columns: _createColumns(),
          rows: _createRows(),
        ),
      ),
    );
  }
}

huangapple
  • 本文由 发表于 2023年8月4日 21:09:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定