如何在Flutter应用中更新和删除Google Sheets中的数据?
Flutter中使用gsheets包实现Google Sheets的更新与删除操作
你已经基于gsheets包实现了Google Sheets的数据创建功能,以下是补充更新指定行和删除指定行/列的具体实现方案,直接整合到你现有代码中即可:
一、更新数据
1. 按行号直接更新整行
在User类中添加以下方法,传入目标行号和要更新的U对象即可:
static Future updateRow(int rowIndex, U user) async { if (us == null) return; // 使用map.updateRow直接更新整行数据 await us!.values.map.updateRow(rowIndex, user.toJson()); }
2. 按Id(唯一标识)查找并更新行
如果需要根据Id字段定位目标行再更新,先添加一个查找行号的方法,再结合更新逻辑:
// 根据Id查找对应的行号(表头行是第1行,数据从第2行开始) static Future<int?> getRowIndexById(String targetId) async { if (us == null) return null; // 获取所有行的Id列数据 final ids = await us!.values.column(Uf.id, fromRow: 2); // 查找目标Id的索引,行号=索引+2(因为从第2行开始) final index = ids.indexOf(targetId); return index != -1 ? index + 2 : null; } // 按Id更新数据 static Future updateById(String targetId, U updatedUser) async { final rowIndex = await getRowIndexById(targetId); if (rowIndex != null) { await updateRow(rowIndex, updatedUser); } }
3. 更新单个单元格
如果只需要更新某一行的某一列数据,可以用以下方法:
static Future updateCell(int rowIndex, String columnName, dynamic value) async { if (us == null) return; // 获取列对应的字母标识(比如Id列对应A列) final columnIndex = await us!.values.map.columnByName(columnName); if (columnIndex != null) { await us!.values.updateCell(rowIndex, columnIndex, value); } }
二、删除数据
1. 删除指定行
在User类中添加删除行的方法:
static Future deleteRow(int rowIndex) async { if (us == null) return; await us!.deleteRow(rowIndex); } // 结合Id查找删除行 static Future deleteById(String targetId) async { final rowIndex = await getRowIndexById(targetId); if (rowIndex != null) { await deleteRow(rowIndex); } }
2. 删除指定列
如果需要删除某一列(比如删除Task列):
static Future deleteColumn(String columnName) async { if (us == null) return; final columnIndex = await us!.values.map.columnByName(columnName); if (columnIndex != null) { await us!.deleteColumn(columnIndex); } }
三、优化初始化逻辑(避免重复插入表头)
你当前的init方法每次都会插入表头到第1行,容易造成重复,建议修改为:
static Future init() async { try { final spreadsheet = await gsheets.spreadsheet(id); us = await getWorkSheet(spreadsheet, title: "staff"); // 检查第1行是否已经是表头,避免重复插入 final firstRow = await us!.values.row(1); if (firstRow.isEmpty || !firstRow.contains(Uf.id)) { await us!.values.insertRow(1, Uf.getF()); } } catch (e) { print(e.toString()); } }
使用示例
// 更新Id为"1001"的用户数据 final updatedUser = U( id: "1001", date: "2024-05-20", company: "New Company", reason: "Updated Reason", calls: "5", handled: "4", status: "Completed", task: "Follow up" ); await User.updateById("1001", updatedUser); // 删除Id为"1002"的行 await User.deleteById("1002"); // 删除第5行 await User.deleteRow(5);
内容的提问来源于stack exchange,提问作者MOBILES RECOVERY
相关产品推荐
相关产品推荐

