简体   繁体   中英

How to fetch the integer from firestore flutter? _TypeError(type 'String' is not a subtype of type 'int)

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'];      
}

Getting this error while fetching avgRating which is stored as a number on Cloud Firestore. I have tried

  1. avgRating = int.parse(snapshot.data()['avg_rating'].toString()); same error
  2. avgRating = snapshot.data()['avg_rating'] as int; typecast error
  3. avgRating = snapshot.data()['avg_rating'].toDouble(); No such method found
  4. avgRating = snapshot.data()['avg_rating'] as num; typecast error

I would really appreciate your help. Thank you

So I tried changing the data type while declaring the value to 'var avgRating' and it worked. If I declare it with int or double it gives the same error. I think because firestore's number type supports multiple data types like int, double.

Thanks for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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