Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<X> - flutter

Shouldn't we be able to assign a value to a field IF IT IS THE SAME TYPE UNDER THE HOOD - E.G. IN THE DEBUGGER IT SAYS IT IS A List<GroceryItmTag>? and you are trying to assign it to a List<GroceryItmTag>?, and just cast it to the correct type or to dynamic? Here I am hovering over formFieldValue, which I later assign to groceryItm.tags:
groceryItem.tags is List<GroceryItmTag>? and I'm assigning to it, a field which is a List<GroceryItmTag>?, under the hood, even though it is not recognised as that. But it is throwing this exception whether I cast it as List<GroceryItmTag>? or I just cast it to dynamic and assign it.
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<GroceryItmTag>?'
How can I assign it without throwing the exception?
This is hovering over groceryItm.tags, the field that I am trying to assign formFieldValue to {List<GroceryItmTag>? tags}:

Shouldn't we be able to assign a value to a field if it is the same type under the hood, and just cast it to the correct type or to dynamic?
No
Simple example. If I have a List<Sheep> and I assign it to a List<dynamic>, now you could suddenly insert a Wolf() into my List<Sheep> through that List<dynamic> variable. Because a Wolf is a dynamic, too and you can insert into a List<dynamic>. That is why it does not work and will not work.
You could assign your List<Sheep> to a plain dynamic though and cast it as neccessary.

A workaround is to filter on the type and assign that. Example:
List<dynamic> list = ['a', 'b', 'c'];
List<String> stringList = list as List<String>; //this will give a runtime error
List<String> stringList = list.whereType<String>().toList(); //workaround

Related

Flutter : Field 'initScreen' should be initialized because its type 'int' doesn't allow null. int initScreen;

Field 'initScreen' should be initialized because its type 'int' doesn't allow null. int initScreen
This code is for onboarding screen that visible only one time, how can i solve this error?
When you're declaring data types like int initScreen or String name and other data types, It means it has an appropriate value.
When the value of the data type will initialize later with some operations and logic, you have to add late before of your data type like late int number.
When you're not sure the value of initializing is null or not, you can declare like this int? number, this mean it can have appropriate value or null.

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Map<String, double>>'

I am very new to using flutter and platform specific code so please forgive me if this is a stupid question. I am using a event channel to return data from android side to flutter. I am returning a List<List<Map<String,double>>> but when it reaches the flutter side, it becomes List dynamic. I want to add the last Map object to another list that I created on the flutter side which has the same type of List<List<Map<String,double>>>.
However, when I tried to add it, it gives an exception, "Unhandled Exception: type 'List' is not a subtype of type 'List<Map<String, double>>'".
This is the list I want to add the Map object to.
List<List<Map<String,double>>> convertedList = [];
This is my adding code. Ignore the print statement.
List<dynamic> t = event;
print( "length ${t.length}");
print("type ${t[t.length-1].runtimeType}");
convertedList.add(t[t.length - 1]);
I have tried methods like cast or from but it did not work for me as the same error came out or maybe i used it the wrong way. I really want to know how can i add the Map object to the list. Thanks so much for your help.
Try:
List<dynamic> t = event;
List<Map<String,double>> newTempList = t[t.length - 1].map((e)=>e as Map<String,double>).toList();
convertedList.add(newTempList);
//Or you can make it shorter by just using this:
List<dynamic> t = event;
convertedList.add(t[t.length - 1].map((e)=>e as Map<String,double>).toList());
Because List<List<Map<String,double>>> is technically also List<dynamic> also, but the opposite is not always true. So you have to cast your items as Map,String, double> first, add those to a list, and then add this newly generated list to your convertedList.

How to initialize Either Right to an empty value in flutter

I recently made the switch to null-safety in my flutter project, which brings a new kind of problem when using the Either type (from the dartz package)
For example, before I would have some properties in my class like this:
Either<Failure, List<Product>> _products;
I would then have a function to get the products, and consume it in my view.
However, now with null safety, I need to initialize this property, because it should never be null, instead I would like to have an empty list.
If I do this
Either<Failure, List<Product?>> _products = [];
I get this error
A value of type 'List<dynamic>' can't be assigned to a variable of type 'Either<Failure, List<Product?>>'.
So my question would be, how can I initialize this property to the right value of Either, with an empty list?
Have this go:
Either<Failure, List<Product?>> _products = right([]);
you can use the new 'late' keyword that fixes this issue
late Either<Failure, List<Product?>> _products;
read more about it here

A value of type 'List<Customer>' can't be assigned to a variable of type 'Future<List<Customer>>'

How to convert 'List' to 'Future<List>'. I need get two type ('List' & 'Future<List>' ) in different places
My api response
var data = jsonDecode(r.body);
custList.add(new Customer(
data[i]['CustomerID'],
'${data[i]['ProfileImageUrl']}' + '${data[i]['ProfileImage']}',
'${data[i]['CompanyName']}',
data[i]['Email'],
data[i]['RegisterNumber'],
data[i]['PhoneNumber'],
data[i]['BillingStreet'],
data[i]['BillingCity'],
data[i]['BillingZip'],
data[i]['MasterCountryName'],
data[i]['MasterStateName'],
data[i]['Type'],
new customeraddress(data[i]['BillingStreet'],
data[i]['BillingCity'], data[i]['BillingZip']),
status,
data[i]['CustomerTaxExemptType'],
data[i]['MasterCountryID'],
data[i]['MasterStateID'],
));
How to convert 'List' to 'Future<List>'.
If you are not entirely sure if you get a T or a Future<T>, you can use the FutureOr<T> (documentation) class.
To create a Future<T> from a value to satisfy some compiler syntax, you can use the named constructor Future.value (documentation).
For more information on Futures: What is a Future and how do I use it?

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast

This exception is thrown in the lins myList = results['users'];. I also tried myList = results['users'] as List<String>;. The type of results['users'] is List<dynamic>. Actually it contains Strings so why can't it be converted?
List<String> myList = List<String>();
results = await ApiService.searchUser();
setState(() {
myList = results['users'];
}
You can build a new list
myList = new List<String>.from(results['users']);
or alternatively, use a cast:
myList = results['users'].cast<String>();
Note that myList.runtimeType will differ:
List<String> in case of a new list
CastList<dynamic, String> in case of a cast
See discussion on Effective Dart: When to use "as", ".retype", ".cast"
I would suggest that you hardly ever use cast or retype.
retype wraps the list, forcing an as T check for every access, needed or not.
cast optionally wraps the list, avoiding the as T checks when not needed, but this comes at a cost of making the returned object polymorphic (the original type or the CastList), which interferes with the quality of the code that can be generated.
If you are going to touch every element of the list, you might as well copy it with
new List<T>.from(original)
So I would only use cast or retype if my access patterns are sparse or if I needed to update the original.
Note that the discussion above refers to retype method, which was removed from Dart 2, but other points are still valid.