Flutter中如何调用Firebase Cloud Function更新Firestore数据?
问题原因与修正方案
1. 云函数端错误修正
你当前的云函数存在3个核心问题:
- 用了
functions.https.onRequest定义普通HTTP接口,但Flutter端用的HttpsCallable仅适配Callable类型云函数,两者不兼容 - 异步时序错误:
res.send(200)写在异步操作外侧,不等Firestore更新完成就提前返回了请求 - 参数读取逻辑错误:原逻辑直接把整个请求body作为数值写入,没有取对应字段的值
修正后的index.js代码如下:
exports.update = functions.https.onCall(async (data, context) => { try { // 读取Callable函数传入的参数 const getNewPercentage = data.percentage; const docRef = admin.firestore().collection('waterpercentage').doc('percentage'); // 等待更新完成再返回 await docRef.update({'percentage': getNewPercentage}); return {code: 200, message: '更新成功'}; } catch (err) { console.log("更新错误: ", err); // 抛出标准Callable错误供前端捕获 throw new functions.https.HttpsError('internal', '更新失败', err); } });
修改完成后重新部署云函数即可生效。
2. Flutter端错误修正
你当前的Flutter代码存在2个核心问题:
- 传参格式错误:
Map的键用了变量percentage,正确应为字符串'percentage',同时泛型需要是<String, dynamic> CloudFunctions是cloud_functions3.0.0版本前的旧API,你当前插件版本已淘汰该接口,统一使用FirebaseFunctions.instance即可
修正后的调用代码如下:
Future<void> updateWaterPercentage() async { try { HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('update'); log("Calling percentage here: "); log(percentage.round().toString()); // 传入键为字符串的参数 final resp = await callable.call(<String, dynamic>{ 'percentage': percentage.round(), }); log("更新结果:${resp.data.toString()}"); } catch (e) { log("调用云函数出错:$e"); } }
内容的提问来源于stack exchange,提问作者WannaInternet
相关产品推荐
相关产品推荐

