【问题标题】:How to fetch the integer from firestore flutter? _TypeError(type 'String' is not a subtype of type 'int)如何从firestore颤振中获取整数? _TypeError(类型“字符串”不是类型“int”的子类型)
【发布时间】:2021-08-02 11:57:17
【问题描述】:

user_repo.dart

Future<List<UserModel>> fetchUsers() async {

    var usercollection = await users.get();
    var userList = usercollection.docs.map((e) => EU.fromSnapShot(e)).toList();
    print("repo: ${userList[1].avgRating}");
    return userList;
    
  }
}

user_model.dart

class UserModel{
  final String user_id;
  final String username;
  String currentProfile = '--';
  double yearsOfExp = 0;
  String smallIntro = "";
  String emailId = "";
  String image;
  int avgRating;
  EU({
    this.user_id,
    this.username,
    this.currentProfile,
    this.smallIntro,
    this.yearsOfExp,
    this.emailId,
    this.image,
  this.avgRating}) ;

  UserModel.fromSnapShot(DocumentSnapshot snapshot)
      : assert(snapshot != null),
        eu_id =
            snapshot.data()['userId'] != null ? snapshot.data()['userId'] : 'null',
        username = snapshot.data()['username'],
        image = snapshot.data()['profile_img_url'],
        emailId = snapshot.data()['email'],
        avgRating =  snapshot.data()['avg_rating'];      
}

在获取以数字形式存储在 Cloud Firestore 中的 avgRating 时出现此错误。我试过了

  1. avgRating = int.parse(snapshot.data()['avg_rating'].toString());同样的错误
  2. avgRating = snapshot.data()['avg_rating'] as int;类型转换错误
  3. avgRating = snapshot.data()['avg_rating'].toDouble();未找到此类方法
  4. avgRating = snapshot.data()['avg_rating'] as num;类型转换错误

非常感谢您的帮助。谢谢

【问题讨论】:

  • snapshot.data()['avg_rating'] 类型是什么?整数还是字符串?
  • 你试过 int.parse(snapshot.data()['avg_rating']);没有 toString ?
  • 是的,我试过没有 .toString 没有帮助。
  • 从 Firestore 中检索到的号码。

标签: database firebase flutter number-formatting


【解决方案1】:

所以我尝试在将值声明为 'var avgRating' 的同时更改数据类型,并且成功了。如果我用 int 或 double 声明它,它会给出相同的错误。我想是因为firestore的数字类型支持int、double等多种数据类型。

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 2020-09-29
    • 2021-02-25
    • 2022-10-13
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多