我有一个从 firebase 集合动态填充的数据表。有商品名称和价格,我希望用户输入数量,然后在另一个数据单元中自动计算总计(价格 * 数量)。我不确定如何将 texteditingcontroller 添加到每个数据单元的每个数量中。当我尝试添加 TextEditingController 时,它适用于所有数据单元。我需要为每个数据源进行计算。
class _FeedTablesState extends State<FeedTables> {
final myController = TextEditingController();
void _printLatestValue() {
print('Second text field: ${myController.text}');
}
@override
void initState() {
super.initState();
// Start listening to changes.
myController.addListener(_printLatestValue);
}
@override
Widget _buildBody(BuildContext context) {
return Material(
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('Items').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return LinearProgressIndicator();
return DataTable2(
columns: [
DataColumn(label: Text('Name')),
DataColumn(label: Text('Price ')),
DataColumn(label: Text('Quantity')),
DataColumn(label: Text('Total')),
// DataColumn(label: Text('Rapper\nname')),
],
rows: _buildList(context, snapshot.data!.docs)
);
},
),
);
}
List<DataRow> _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return snapshot.map((data) => _buildListItem(context, data)).toList();
}
DataRow _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return DataRow(cells: [
DataCell(Text(record.name.toString())),
DataCell(Text(record.price.toString())),
DataCell(TextField(
controller: myController,
maxLength: 4,
decoration: InputDecoration(
labelText: 'Qty',
labelStyle: TextStyle(fontSize: 9),
counterText: "",
),
),),
DataCell(Text((record.price.toString()))),
// DataCell(Text(record.total_quantity.toString())),
]);
}
@override
Widget build(BuildContext context) {
return _buildBody(context);
}
}
class Record {
final String name;
final String price;
final String quantity;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {required this.reference})
: assert(map['name'] != null),
assert(map['price'] != null),
assert(map['quantity'] != null),
name = map['name'],
price = map['price'],
quantity = map['quantity'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data() as Map<String, dynamic>, reference: snapshot.reference);
@override
String toString() => "Record<$name:$price:$quantity:>";
}