flutterdartdatarow

How do i modify the value of DataRow in flutter?


I have a 2 DataRow that I query from the firebase database and I want to multiply the value of qty with the value in total, I have the value of 1 in a variable qty as shown here int qty = 1; in my code as a default quantity.

enter image description here

For example, the value of Qty which is 1 multiply by the value of the total as it was in the sample code below.

Container _itemTatble() {
return Container(
  width: MediaQuery.of(context).size.width,
  padding: const EdgeInsets.only(top: 10, right: 8, left: 8),
  child: Scrollbar(
    thumbVisibility: true,
    trackVisibility: true,
    child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        reverse: true,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                reverse: true,
                child: buildDataTable()),
          ],
        )),
  ),
);}


     Widget buildDataTable() {
return StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('Products')
        .snapshots(includeMetadataChanges: true),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasError) {
        return Text('Something went wrong! ${snapshot.error}');
      } else if (snapshot.hasData) {
        final columns = ['Items', 'Price', 'Qty', 'Total'];
        return DataTable(
            columnSpacing: 350,
            showCheckboxColumn: false,
            columns: getcolumns(columns),
            rows: _createRows(snapshot.data));
      } else {
        return const Center(child: CircularProgressIndicator());
      }
    });}   


List<DataColumn> getcolumns(List<String> columns) => columns
  .map((String column) => DataColumn(
      label: Text(column, style: Defaults.drawerTextBlacknormal)))
  .toList();



 List<DataRow> _createRows(QuerySnapshot snapshot) {
List<DataRow> newList = snapshot.docs.map((DocumentSnapshot document) {
  Map<String, dynamic> data = document.data()! as Map<String, dynamic>;   


  return DataRow(
    cells: [
      DataCell(Text(data['Items'].toString(),
          style: Defaults.drawerTextBlacknormal)),
      DataCell(Text(data['Price'].toString(),
          style: Defaults.drawerTextBlacknormal)),
      DataCell(
          TextFormField(
            initialValue: '${qty}',
            onChanged: (insertValue) => setState(() {
              qty = int.parse(insertValue);
            }),
          ),
          showEditIcon: true),
      DataCell(Text("${qty * data['Price']}",
          style: Defaults.drawerTextBlacknormal)),
    ],
    onSelectChanged: ((bool? selected) =>
        selected == null ? selected = false : selected = true),
  );
}).toList();
return newList;
}  

Now! I can successfully modify the value of qty and multiply it by the value in total. But my problem is, that the modification also applied to the second row as shown here.

enter image description here

How do I fix this so that each row can be modified separately? Please if anyone knows how to overcome this issue please help. Thank


Solution

  • You need to create/maintain a list of qty that is List<int> qty = []; (or Map of qty something like Map<SomeUniqueKey, int>) instead of int qty = 1; to keep track of individual text-fields.

    So if there are 10 records, 10 qtys and multiply the correct qty from the list with the data[price].