发生异常。_TypeError(类型"Null"不是类型"可迭代"的子类型<dynamic>)



我正在构建一个电子商务应用程序,我创建登录屏幕的方式是,当用户输入凭据并点击登录按钮时,下面的所有信息都会显示(id、名称、电子邮件、密码、地址、类型、令牌、购物车(,应用程序运行正常,但是当我尝试使用我的凭据登录时,这个错误">"("发生异常。_TypeError(类型"Null"不是类型"Iterable"的子类型("会出现在我的代码上,特别是在找到"cart"的区域。当我注释掉"购物车"时,错误不会再次弹出,我可以在登录时正常读取凭据

import 'dart:convert';

class User {
final String id;
final String name;
final String email;
final String password;
final String address;
final String type;
final String token;
final List<dynamic> cart;

User({
required this.id,
required this.name,
required this.email,
required this.password,
required this.address,
required this.type,
required this.token,
required this.cart,
});

Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'email': email,
'password': password,
'address': address,
'type': type,
'token': token,
'cart': cart,
};
}

factory User.fromMap(Map<String, dynamic> map) {
return User(
id: map['_id'] ?? '',
name: map['name'] ?? '',
email: map['email'] ?? '',
password: map['password'] ?? '',
address: map['address'] ?? '',
type: map['type'] ?? '',
token: map['token'] ?? '',
cart: List<Map<String, dynamic>>.from(
map['cart']?.map(
(x) => Map<String, dynamic>.from(x), **...where my error appears...**
),
),
);
}

String toJson() => json.encode(toMap());

factory User.fromJson(String source) => User.fromMap(json.decode(source));

User copyWith({
String? id,
String? name,
String? email,
String? password,
String? address,
String? type,
String? token,
List<dynamic>? cart,
}) {
return User(
id: id ?? this.id,
name: name ?? this.name,
email: email ?? this.email,
password: password ?? this.password,
address: address ?? this.address,
type: type ?? this.type,
token: token ?? this.token,
cart: cart ?? this.cart,
);
}
}

更改此

cart: List<Map<String, dynamic>>.from(
map['cart']?.map(
(x) => Map<String, dynamic>.from(x),
),
),

到这个

cart: List<Map<String, dynamic>>.from(
map['cart']?.map(
(x) => Map<String, dynamic>.from(x), 
) ?? [],
),

如果map['cart']为null,那么您正在从null创建List,这就是为什么会出现错误的原因。如果为null,则必须传递空列表。

最新更新