我有一个 flutter 应用程序,用户可以在其中填写一份长表单。但我想添加另一个按钮,当用户想要单击并上传具有与表单相同的数据的“excel 或电子表格或 CSV”时,该数据存储在 firebase firestore 中。 请帮助我克服这个问题。
它是试用版,但运行完美
和 csv 包 并尝试点击此功能(此功能会将.csv文件中的所有数据获取到您的应用程序)
var csvData = <List<dynamic>>[].obs;
Future<void> pickFile() async {
try {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
PlatformFile file = result.files.first;
if (file.path != null) {
final input = File(file.path!).openRead();
final fields = await input
.transform(utf8.decoder)
.transform(const CsvToListConverter())
.toList();
csvData.value = fields;
print(">>>>>>>>>>>>CSV Data: $fields");
} else {
Get.snackbar('Error', 'File path is null.');
}
} else {
Get.snackbar('Error', 'No file selected.');
}
} catch (e) {
Get.snackbar('Error', 'Failed to pick the file: $e');
}
}
List<List<String>> skippedRows = [];
var uploadComplete = false.obs;
Future<void> uploadLeadsToFirestore() async {
skippedRows.clear();
if (csvData.isNotEmpty) {
for (int i = 1; i < csvData.length; i++) {
final row = csvData[i];
// Check if required fields are not empty (if empty then skip them)
if (row.length > 0 &&
row[0].toString().isNotEmpty &&
row.length > 1 &&
row[1].toString().isNotEmpty &&
row.length > 2 &&
row[2].toString().isNotEmpty &&
row.length > 4 &&
row[4].toString().isNotEmpty &&
row.length > 5 &&
row[5].toString().isNotEmpty) {
// Mapping row to lead fields
final leadData = {
'leadName': row.length > 0 && row[0].toString().isNotEmpty
? row[0].toString()
: null,
'leadEmail': row.length > 1 && row[1].toString().isNotEmpty
? row[1].toString()
: null,
'leadPhone': row.length > 2 && row[2].toString().isNotEmpty
? row[2].toString()
: null,
'propertySize': row.length > 3 && row[3].toString().isNotEmpty
? row[3].toString()
: null,
'city': row.length > 4 && row[4].toString().isNotEmpty
? row[4].toString()
: null,
'projectName': row.length > 5 && row[5].toString().isNotEmpty
? row[5].toString()
: null,
'status': 'New Lead',
'label': 'Hot',
'lastAction': '',
'createdByUid': createdByUid,
'createdAt': FieldValue.serverTimestamp(),
'updatedAt': FieldValue.serverTimestamp(),
};
await FirebaseFirestore.instance.collection('leads').add(leadData);
} else {
// Convert row elements to String before adding to skippedRows
skippedRows.add(row.map((e) => e.toString()).toList());
}
}
uploadComplete.value = true;
Get.snackbar('Success', 'Leads uploaded successfully!');
} else {
Get.snackbar('Error', 'No data to upload.');
}
}