Flutter || Firestore:从Firestore取数后如何生成DataRow列表供DataTable使用
问题原因
- 你声明的
dataRowList未初始化,循环内生成的DataRow没有被添加到列表中 - 方法最终固定返回
null,没有返回生成的列表 - 缺少空值安全校验,
allData或内部字段为null时会触发运行异常
修正后的buildList方法代码
List<DataRow> buildList(List? allData){ // 初始化空的DataRow列表,allData为空时直接返回空列表 List<DataRow> dataRowList = []; if (allData == null) return dataRowList; for(int i =0; i < allData.length; i++){ var item = allData[i]; dataRowList.add(DataRow(cells: [ DataCell(Text(item['customerNumber'] ?? '')), DataCell(Text(item['Name'] ?? '')), DataCell(Text(item['TCKN'] ?? '')), DataCell(Text(item['VKN'] ?? '')), DataCell(Text(item['paketAdi'] ?? '')), DataCell( Text( item['status'] ?? '', style: TextStyle( color: item['status'] == "Tamamlandı" ? Colors.green : item['status'] == "İşlem Başarısız" ? Colors.red : item['status'] == "Belgeler Bankada" ? Colors.cyanAccent : Colors.blue), ), ), DataCell(Text(item['startDate'] ?? '')), DataCell(Text(item['endDate'] ?? '')), ])); } return dataRowList; }
可选简化写法(用map替代循环)
你也可以直接用map方法生成列表,代码更简洁:
List<DataRow> buildList(List? allData) { return allData?.map((item) => DataRow(cells: [ DataCell(Text(item['customerNumber'] ?? '')), DataCell(Text(item['Name'] ?? '')), DataCell(Text(item['TCKN'] ?? '')), DataCell(Text(item['VKN'] ?? '')), DataCell(Text(item['paketAdi'] ?? '')), DataCell( Text( item['status'] ?? '', style: TextStyle( color: item['status'] == "Tamamlandı" ? Colors.green : item['status'] == "İşlem Başarısız" ? Colors.red : item['status'] == "Belgeler Bankada" ? Colors.cyanAccent : Colors.blue), ), ), DataCell(Text(item['startDate'] ?? '')), DataCell(Text(item['endDate'] ?? '')), ])).toList() ?? []; }
修改后无需调整你现有FutureBuilder里的调用逻辑,直接传入rows: buildList(allData)即可正常使用。
内容的提问来源于stack exchange,提问作者Çağlar Binici
相关产品推荐
相关产品推荐

