The argument type 'ListOf5' can't be assigned to the parameter type 'ListOf5' - dart

I need to implement an abstract class function, which own a an specific data type. But I need inside my logic layer to make the attribute which is going to be passed as a dynamic data type. But when i Pass it to the function, i am sure that its data type will be as needed. So, i type (product.value.pickedImages) as ListOf5) . But it does an Exception.
The Abstract Class Code Is:
Future<Either<FireStoreServerFailures, List<String>>> uploadProductImages(
{required ListOf5<File> images});
The Implementation Code Is:
Future<Option<List<String>>> _uploadImagesToFirestorage() async {
return await productRepo
.uploadProductImages(
images: (product.value.pickedImages) as ListOf5<File>) // Exception
}
The Exception Is:
The argument type 'ListOf5 < dynamic>' can't be assigned to the
parameter type 'ListOf5 < File>'.

You are trying to cast the List from List<dynamic> to List<String>.
Instead, you should cast each item, using something like this:
void main() {
List<dynamic> a = ['qwerty'];
print(List<String>.from(a));
}
Not sure about the implementation of this ListOf5 though...

The cast (product.value.pickedImages) as ListOf5<File> fails.
It fails because product.value.pickedImages is-not-a ListOf5<File>, but instead of ListOf5<dynamic> (which may or may not currently contain only File objects, but that's not what's being checked).
Unlike a language like Java, Dart retains the type arguments at run-time(it doesn't do "erasure"), so a ListOf5<dynamic> which contains only File objects is really different from a ListOf5<File> at run-time.
You need to convert the ListOf5<dynamic> to a ListOf5<File>.
How to do that depends on the type ListOf5, which I don't know.
For a normal List, the two most common options are:
(product.value.pickedImages).cast<File>(). Wraps the existing list and checks on each read that you really do read a File. It throws if you ever read a non-File from the original list. Perfectly fine if you'll only read the list once.
List<File>.of(product.value.pickedImages). Creates a new List<File> containing the values of product.value.pickedImages, and throws if any of the values are not File objects. Requires more memory (because it copies the list), but fails early in case there is a problem, and for small lists, the overhead is unlikely to be significant. If you read the resulting list many times, it'll probably be more efficient overall.
If the ListOf5 class provides similar options, you can use those. If not, you might have to build a new ListOf5 manually, casting each element of the existing ListOf5<dynamic> yourself.
(If the ListOf5 class is your own, you can choose to add such functionality to the class).

Related

What does it mean <> in method?

I have this method
#override
Response<BodyType> convertResponse<BodyType, SingleItemType>(
Response response) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody =
_convertToCustomObject<SingleItemType>(dynamicResponse.body);
return dynamicResponse.replace<BodyType>(body: customBody);
}
What does it mean <BodyType> and <BodyType, SingleItemType> in this method?
These are called generics in Dart (in fact, they are called the same in other similar programming languages).
The main idea behind generics is that you could reuse the same code without relying on a specific data/return type. Imagine List in Dart. You could have a list of integers (List<int>), a list of strings (List<String>), a list of your custom objects (List<CustomType>) - the type is not hardcoded and it could be adjusted based on your needs.
Also, you could say that it would be easier just to use dynamic or Object types that would cover most of these cases. However, generics brings you type safety, and the method type itself becomes a parameter.
Here is the official documentation about generics.

Is there a modifiable Iterable type?

I need a modifiable collection like a List or a Set to be passed as a parameter. Using Iterable doesn't guarantee this argument to have methods like add or remove.
Example method:
void foo(Iterable bar) {
bar.add(); // The method 'add' isn't defined for the type 'Iterable'.
}
Is there a class / interface for (modifiable) collections which guarantees those methods? If not, why?
There is not a modifiable type. Very early (before Dart 1) we had some other types in our hierarchy, but we decided to avoid including them because things were getting a bit too complex.
I still wish we'd shipped a List interface without the mutation members. 🤷

Instantiating a class by String name in Dart

I am trying to call a method of a class that I only know by name as a String. Now therefore I would need a ClassMirror of that class that allowes me to instantiate an instance. However, creating ClassMirrors seems to be only possible by entering a type using reflectClass(Type) or by passing an already existing instance of that class into reflect(dynamic). So these aren`t helping if I only have a String.
In Java you can do this pretty easily, by calling Class.forName(String). Then you would get a Constructor instance, make it accessibly and call it.
Does anyone know if this is even possible in dart? What seems weird is that once you have a ClassMirror you can access fields and methods by passing symbols, which can be created by Strings.
You can put a specific list of strings to map to a specific list of closures to create a new object with specific parameters.
But you can't get a reflection without using dart:mirrors, which is being deprecated, and also had a negative impact on tree shaking to get the payload size down.
In general, you're invited to look at the package:reflectable to achieve most of what you'd want out of dart:mirrors, using source-to-source builders.

Why is Dart's Datetime.parse not a factory constructor?

Dart's Datetime class has a number of named constructors, but DateTime.parse() is not one of them. Instead, DateTime.parse() is a static method which returns a DateTime. To me, it makes sense as a constructor (since you are generating a new DateTime object in a manner not too different from the Datetime.utc() constructor).
Theories I've come up with are to mirror the fact that int.parse is not a constructor or to allow easier chaining (you don't need to use the cascade operator with a static method). But maybe there is another reason that I'm not thinking of. Does anyone know why they didn't make it a named constructor?
More explanation for the same change for Uri.parse: http://permalink.gmane.org/gmane.comp.lang.dart.general/17081
"parse" is special. The question is: do you see parsing as an
operation that does something and ends up giving you the result, or do
you see the string as data to construct a new element. If you see it
as the earlier, then "parse" should be a static function. If you see
the string as the data, then it should be a named constructor.
And then, of course, there is consistency.

How does Orika decide when to use converter

I am trying to understand when does Orika use converters to do the mapping versus direct casting.
I have the following mapping:
Class A {
Map<String, Object> props;
}
Class B {
String bStr;
int bInt;
}
My mapping is defined as props['aStr'] => bStr and props['aInt'] => bInt
When I look at the generated code, I see that for the String case, it uses a converter and calls its convert method for the transformation:
destination.setBStr("" + ((ma.glasnost.orika.Converter)usedConverters[0]).convert(
((java.lang.Object) ((java.util.Map) source.getProps().get("aStr"),
(ma.glasnost.orika.metadata.Type) usedTypes[0]))
But, for the integer case it directly casts it like this:
destination.setBInt((java.lang.Integer)(java.lang.Object) ((java.util.Map)
source.getProps().get("aInt")))
The above line of code ends up giving class cast exception.
For fixing this issue, I was thinking along the lines of using a custom converter but if the above line of code doesn't use the converter then that wont work.
Of course, I can always do this is in my custom mapper but just trying to understand how the code is generated for type conversion.
Thanks!!
In Orika there is two stages: config-time and runtime, as optimization Orika resolve all used converter in the config-time and cache them into each generated mapper so it will be accessible directly O(1) but in the config time it will try to find in a list O(n) of registered converters which one "canConvert" between two given types, canConvert is a method in Converter interface .
So this solution offer the best of the two worlds:
A very flexible way to register a converter with arbitrary conditions
An efficient resolution and conversion operation in the runtime.
Orika by default, leverage the existence of .toString in every object to offer implicit coercion to String for every Object. The problem here is that there is no Converter from Object to Integer.
Maybe this can be an issue of error reporting. Ideally Orika should report that an Object have to be converted to Integer and there is no appropriate converter registered.

Resources