如何通过StreamBuilder解决Flutter数据表格错误:“预期值类型为'List',但实际类型是'List'?”
如何通过StreamBuilder解决Flutter数据表格错误:“预期值类型为'List',但实际类型是'List'?”
在代码中,使用StreamBuilder以流的方式从云Firestore中获取数据,并在数据表格小部件中显示它,但是当我运行代码时,它会给出我上面提到的错误。
SizedBox( width: double.infinity, child: StreamBuilder( stream: FirebaseFirestore.instance.collection('products').snapshots(), builder: (BuildContext context,snapshot) { (!snapshot.hasData)? Center(child: CircularProgressIndicator()) : DataTable( // columnSpacing: defaultPadding, columns: [ DataColumn(label: Text("Id")), DataColumn(label: Text("Name")), DataColumn(label: Text("Category")), DataColumn(label: Text("Image")), DataColumn(label: Text("Original Price")), DataColumn(label: Text("Sale Price")), DataColumn(label: Text("Discount")), DataColumn(label: Text("Commission")), DataColumn(label: Text("Date")), ], rows: _listofRows(snapshot.data), ); })),
这里是_listofRows方法的代码
List _listofRows(snapshot) { List newList = snapshot.docs.map((docSnapshot) { return DataRow(cells: [ DataCell(Text(docSnapshot.data()['ProductID'].toString())), DataCell(Text(docSnapshot.data()['Product Name'].toString())), DataCell(Text(docSnapshot.data()['Category Name'].toString())), DataCell(Text(docSnapshot.data()['Product ImageUrl'].toString())), DataCell(Text(docSnapshot.data()['originalPrice'].toString())), DataCell(Text(docSnapshot.data()['salePrice'].toString())), DataCell(Text(docSnapshot.data()['Discount'].toString())), DataCell(Text(docSnapshot.data()['Commission Rate'].toString())), DataCell(Text(doctSnapshot.data()['Out of Stock Date'].toString())), ]); }).toList(); return newList; }
这是云Firestore数据库中产品集合的文档示例之一。(产品文档链接)
admin 更改状态以发布 2023年5月24日
解决方案是为map方法提供一个类型参数。
List_listofRows(snapshot) { List newList = snapshot.docs.map ((docSnapshot) { return DataRow(cells: [ DataCell(Text(docSnapshot.data()['ProductID'].toString())), DataCell(Text(docSnapshot.data()['Product Name'].toString())), DataCell(Text(docSnapshot.data()['Category Name'].toString())), DataCell(Text(docSnapshot.data()['Product ImageUrl'].toString())), DataCell(Text(docSnapshot.data()['originalPrice'].toString())), DataCell(Text(docSnapshot.data()['salePrice'].toString())), DataCell(Text(docSnapshot.data()['Discount'].toString())), DataCell(Text(docSnapshot.data()['Commission Rate'].toString())), DataCell(Text(doctSnapshot.data()['Out of Stock Date'].toString())), ]); }).toList(); return newList; }
如果你想了解更多内容,可以查看一个类似的答案,它会出现类型推断的意外失败。
[感谢@Jonah Williams]: https://stackoverflow.com/users/4231909/jonah-williams