【问题标题】:_TypeError (type 'String' is not a subtype of type 'int' of 'index') on profile.dartprofile.dart 上的 _TypeError(类型 \'String\' 不是 \'index\' 的类型 \'int\' 的子类型)
【发布时间】:2023-02-10 18:16:19
【问题描述】:
当我修复它时,我试图调用用户出现在个人资料页面中应用程序块我遇到了其他问题,如果有任何解决方案可以帮助我,就是这个问题
import 'package:flutter/foundation.dart';
class UserModel {
String? uid;
String? Username;
String? email;
String? photoUrl;
UserModel(
{this.uid, this.email, this.Username, this.photoUrl});
// receving data from the server
factory UserModel.fromMap(Map) {
return UserModel(
uid: Map['userId'],
Username: Map['Username'],
email: Map['email'],
photoUrl: Map['photoUrl'],
);
}
// /// sending data to firestore
Map<String, dynamic> toMap() {
return {
'userId': uid,
'Username': Username,
'email': email,
'photoUrl': photoUrl,
};
}
}
错误图片
【问题讨论】:
标签:
flutter
firebase
dart
google-cloud-firestore
【解决方案1】:
不要使用 Map 作为变量名,它是一个数据类型
factory UserModel.fromMap(map) {
return UserModel(
uid: map['userId'],
Username: map['Username'],
email: map['email'],
photoUrl: map['photoUrl'],
);
}
【解决方案2】:
通过使用这个:
// receving data from the server
factory UserModel.fromMap(Map) {
return UserModel(
uid: Map['userId'],
Username: Map['Username'],
email: Map['email'],
photoUrl: Map['photoUrl'],
);
}
您在输入时指的是 Map,因此它会抛出错误。
你需要引用 Map 对象,而不是 Map 类型,所以试试这个:
// receving data from the server
factory UserModel.fromMap(Map data) {
return UserModel(
uid: data['userId'],
Username: data['Username'],
email: data['email'],
photoUrl: data['photoUrl'],
);
}
【解决方案3】:
在传输数据时,您需要将响应声明为 Map<String, dynamic>?即使在这样做之后如果错误仍然存在,请尝试添加 Map['userId].toString() ||映射 ['userId] 作为字符串。参考下面的代码
final favoriteResponse = await http.get(url);
final favoriteData =
json.decode(favoriteResponse.body) as Map<String, dynamic>?;
final List<Product> loadedProducts = [];
extractedData?.forEach((prodId, prodData) {
loadedProducts.add(Product(
id: prodId,
title: prodData['title'],
description: prodData['description'],
price: prodData['price'],
imageUrl: prodData['imageUrl'],
isFavorite:
favoriteData == null ? false : favoriteData[prodId] ?? false));
});
_items = loadedProducts;
notifyListeners();
}
【解决方案4】:
确保
用户身份
是您的 Firestore 中的一个字符串