Dart Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Iterable<Map<dynamic, dynamic>>' in type cast
290
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;
}
Author by
Akash Rajoria
Updated on January 02, 2023Comments
-
Akash Rajoria 1 minute
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.-
Chris Pi 12 monthsYou can't cast an 'Iterable<Map<dynamic,dynamic>>` on a simple
List<dynamic>
. You're totally confusing the compiler with half inferred and half declared types. What I mean is, that your Parameter is of type List<dynamic> and later you're trying to cast (not parse!) it to a complete other structure. You should try to either be precise with types or else let Dart infer the types (as far as its possible) itself. If not, you can run into serious problems.
-