FlutterFlow自定义函数调用Firebase查询获取用户名失败求助
解决FlutterFlow自定义函数中Firebase查询返回用户名的问题
问题根源
你的代码存在两个核心问题:
- 异步操作逻辑错误:Firestore查询是异步操作,你用
then回调处理结果,但函数会直接返回初始的空字符串,等异步操作完成时函数已经执行完毕,无法更新返回值。 - FlutterFlow环境适配问题:在FlutterFlow自定义函数中,不能直接使用
FirebaseFirestore.instance,需要使用平台内置的后端API来操作Firebase。
正确实现代码
在FlutterFlow中,需要将函数改为异步类型,并调用内置的Firestore操作方法:
import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:intl/intl.dart'; import 'package:timeago/timeago.dart' as timeago; import '../../flutter_flow/lat_lng.dart'; import '../../flutter_flow/place.dart'; import '../../flutter_flow/custom_functions.dart'; import '../../backend/backend.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import '../../auth/auth_util.dart'; Future<String?> userToNameFxn(DocumentReference? usr) async { /// MODIFY CODE ONLY BELOW THIS LINE if (usr == null) return ''; // 直接通过传入的DocumentReference获取用户文档 final userDocSnapshot = await usr.get(); if (userDocSnapshot.exists) { return userDocSnapshot.data()?['display_name'] as String? ?? ''; } // 如果传入的引用对应的是uid而非文档ID,可启用以下查询逻辑 // final querySnapshot = await usersCollection.where('uid', isEqualTo: usr.id).get(); // if (querySnapshot.docs.isNotEmpty) { // return querySnapshot.docs.first.data()['display_name'] as String? ?? ''; // } return ''; /// MODIFY CODE ONLY ABOVE THIS LINE }
关键修改说明
- 改为异步函数:返回类型设为
Future<String?>,添加async关键字,用await等待Firestore操作完成,确保拿到结果后再返回。 - 直接使用传入的引用:如果
usr是用户文档的直接引用,无需额外查询,直接调用get()获取文档数据即可。 - 空值安全处理:增加
usr == null的判断,避免空指针异常;文档不存在或字段为空时返回默认空字符串。
原问题详情
我想在FlutterFlow的自定义函数里用Dart代码查询Firebase,实现一个接收DocumentReference参数、返回对应用户display_name字符串的函数,但试了多种写法都报错,发现FlutterFlow无法识别Firebase库。
错误截图

尝试的第一段代码
import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:intl/intl.dart'; import 'package:timeago/timeago.dart' as timeago; import '../../flutter_flow/lat_lng.dart'; import '../../flutter_flow/place.dart'; import '../../flutter_flow/custom_functions.dart'; import '../../backend/backend.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import '../../auth/auth_util.dart'; String? userToNameFxn(DocumentReference? usr) { /// MODIFY CODE ONLY BELOW THIS LINE var tmp = ''; // Get a reference to the Firestore database //final _db = FirebaseFirestore.instance; // Get a reference to the "users" collection //CollectionReference users = _db.collection('users'); // Define the ID of the user you want to retrieve String userId = "$usr?.id"; // Retrieve the user with the specified ID /*DocumentReference user = users.document(userId); user.get().then((DocumentSnapshot snapshot) { // Print the user data tmp = snapshot.data as String; }); final db = FirebaseFirestore.instance; db .collection("users") .where("uid", isEqualTo: userId) .snapshots() .listen((event) { tmp = event.docs[0].data()["display_name"]; });*/ // Get a reference to the Firestore database var db = FirebaseFirestore.instance; // Create a reference to the "users" table var usersRef = db.collection('users'); // Create a query to filter the documents by the "uid" field var query = usersRef.where('uid', isEqualTo: userId); // Get the first matching document query.get().then((querySnapshot) { if (querySnapshot.size > 0) { // There is a matching document, so you can get the data from the first result var firstResult = querySnapshot.docs[0]; var data = firstResult.data(); // Get the display_name field from the data var displayName = data['display_name']; tmp = displayName; // Do something with the display_name... } else { // There are no matching documents tmp = ''; } }); return tmp; /// MODIFY CODE ONLY ABOVE THIS LINE }
尝试的第二段代码
import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:intl/intl.dart'; import 'package:timeago/timeago.dart' as timeago; import '../../flutter_flow/lat_lng.dart'; import '../../flutter_flow/place.dart'; import '../../flutter_flow/custom_functions.dart'; import '../../backend/backend.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import '../../auth/auth_util.dart'; String? userToNameFxn(DocumentReference? usr) { /// MODIFY CODE ONLY BELOW THIS LINE // Get a reference to the Firestore database final db = FirebaseFirestore.instance; // Create a reference to the "users" table var usersRef = db.collection('users'); // Create a query to filter the documents by the "uid" field var query = usersRef.where('uid', isEqualTo: usr?.id); // Get the first matching document query.get().then((querySnapshot) { if (querySnapshot.size > 0) { // There is a matching document, so you can get the data from the first result var firstResult = querySnapshot.docs[0]; var data = firstResult.data(); // Get the display_name field from the data var displayName = data['display_name']; return displayName; } }); return ''; /// MODIFY CODE ONLY ABOVE THIS LINE }
测试函数时的错误截图

内容的提问来源于stack exchange,提问作者Youssof
相关产品推荐
相关产品推荐

