[英]Extra Positional Argument in Flutter/Firebase when trying to access document field
I'm trying to print a specific users info from firebase, but whenever I try to call the specific value, such as name, it always comes up as the error, Too many positional arguments: 0 expected, but 1 found.我正在尝试打印来自 firebase 的特定用户信息,但每当我尝试调用特定值(例如名称)时,它总是出现错误,位置 arguments 太多:预期为 0,但找到 1。
getUserState() async{
String temp;
final FirebaseAuth auth = FirebaseAuth.instance;
final String id = FirebaseFirestore.instance.collection('users').id;
FirebaseFirestore.instance.collection('users').doc(id).get().then((value){
temp = value.data('name') as String;
});
data
is a method that takes no parameter and returns a Map
data
是一种不带参数并返回Map
的方法
Try this:试试这个:
temp = value.data()!['name'] as String;
To print an specific user information from Firebase calling by a value such as name, you can use the Firebase Database Query API. You can use the orderByChild() method to query the database and retrieve data based on a specific value.要打印来自 Firebase 通过名称等值调用的特定用户信息,您可以使用 Firebase 数据库查询 API。您可以使用 orderByChild() 方法查询数据库并根据特定值检索数据。 For example, if you want to print an user information from Firebase calling by name, you can use the following code:
例如,如果要打印一个来自Firebase按姓名调用的用户信息,可以使用如下代码:
// Get a reference to the database
var database = firebase.database();
// Query the database for user information based on name
var query = database.ref("users").orderByChild("name").equalTo("John Doe");
// Get the user information from the query
query.once("value", function(snapshot) {
var userInfo = snapshot.val();
// Print the user information
console.log(userInfo);
});
You can use .get
to read map您可以使用
.get
读取 map
temp = value.get('name') as String? ?? "" ;
If you need a function that returns a String that contains the name you can refactor your code like the following:如果您需要一个返回包含名称的字符串的 function,您可以像下面这样重构您的代码:
Future<String?> getUserState(String userId) async {
final docRef = await FirebaseFirestore.instance.collection('users').doc(userId).get();
final user = docRef.data();
return user?['name'];
}
user : is a Map<String, dynamic> representation of your document in collection. user :是集合中文档的 Map<String, dynamic> 表示。 You can use it to covert in your model with fromJson for example.
例如,您可以使用它来使用 fromJson 来隐藏您的 model。
If any users found with provided id it returns null如果找到任何具有提供的 ID 的用户,它会返回 null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.