繁体   English   中英

尝试访问文档字段时 Flutter/Firebase 中的额外位置参数

[英]Extra Positional Argument in Flutter/Firebase when trying to access document field

我正在尝试打印来自 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是一种不带参数并返回Map的方法

试试这个:

    temp = value.data()!['name'] as String;

要打印来自 Firebase 通过名称等值调用的特定用户信息,您可以使用 Firebase 数据库查询 API。您可以使用 orderByChild() 方法查询数据库并根据特定值检索数据。 例如,如果要打印一个来自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);
    });

您可以使用.get读取 map

 temp = value.get('name') as String? ?? "" ;

如果您需要一个返回包含名称的字符串的 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 :是集合中文档的 Map<String, dynamic> 表示。 例如,您可以使用它来使用 fromJson 来隐藏您的 model。

如果找到任何具有提供的 ID 的用户,它会返回 null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM