Reputation: 75
I was working on a flutter app and when I upgraded it to Flutter 2.0 a new error started occurring. It is an error regarding typecasting but I am not sure why is it occurring as there was no problem with it with the older version. The error is as follows:
Dart Unhandled Exception: type 'List<dynamic>' is not a subtype of
type 'Iterable<Map<dynamic, dynamic>>' in type cast, stack trace: #0 UserModel._convertCartItems (package:test_app/model/user.dart:67:31)
E/flutter (30545): #1 new UserModel.fromSnapshot (package:test_app/model/user.dart:58:12)
E/flutter (30545): #2 UserServices.getUserById.<anonymous closure> (package:test_app/services/user.dart:33:26)
E/flutter (30545): <asynchronous suspension>
E/flutter (30545): #3 UserProvider._onStateChanged (package:test_app/provider/user.dart:125:20)
E/flutter (30545): <asynchronous suspension>
E/flutter (30545):
The code associated with it is :
List<CartItemModel> _convertCartItems(List cart) {
List<CartItemModel> convertedCart = [];
for (Map cartItem in cart as Iterable<Map<dynamic, dynamic>>) {
convertedCart.add(CartItemModel.fromMap(cartItem));
}
return convertedCart;
}
I tried to remove the as Iterable<>
but then the app just rendered one time and started a new error.
Upvotes: 3
Views: 1664
Reputation: 1091
You can try this without for loop :
List<CartItemModel> _convertCartItems(List cart) {
List<CartItemModel> convertedCart = [];
convertedCart = cart.map((e) => CartItemModel.fromJson(e)).toList();
return convertedCart;
}
Upvotes: 1
Reputation: 2541
Your cart
variable is a List, not a Map. You need to change iteration process to this:
for (final rawCartItem in cart) {
convertedCart.add(CartItemModel.fromMap(rawCartItem));
}
Upvotes: 1