dart, overloading [] operator? - operator-overloading

Is it possible to overload the index[] syntax for a collection/iterable type? for example I am writing a SortedList<T> class that wraps around a standard List<T>. and I'd just like to pass on the usage from my sorted list straight down to the underlying list object. I thought I'd read about this on the dart language tour but I can't find it now.

Dart editor seems pretty happy with:
operator [](int i) => list[i]; // get
operator []=(int i, int value) => _list[i] = value; // set
Try it in DartPad

Yes you can override operators. Like this:
T operator [](int index) => items[index];
But you can't overload anything in dart. Because Dart does not support operator or function overloading. That means your class can't have two function with same name but different parameters.

Related

Dynamic Type Casting in Dart/Flutter

I am in the middle of writing a library to dynamically serialise/deserialise any object in Dart/Flutter (Similar in idea to Pydantic for Python). However, I am finding it impossible to implement the last component, dynamic type casting. This is required in order convert types from JSON, such as List to List (or similar). The types are retrieved from objects using reflection.
The below is the desired implementation (though as far as I understand this is not possible in Dart).
Map<String, Type> dynamicTypes = {"key": int };
// Regular casting would be "1" as int
int value = "1" as dynamicTypes["key"];
Is there some workaround which makes this possible to implement? Or have I reached a dead end with this (hence no other dynamic serialisation/deserialisation package already exists).
Conducting more research into this issue, it seems in Dart's current implementation this is impossible due to runtime reflection being disabled as referenced here in the official docs.
There are ongoing discussions about the support for this and the associated package dart:mirrors here on GitHub, but so far though there is some desire for such functionality it is highly unlikely to ever be implemented.
As a result, the only options are:
Use code generation libraries to generate methods.
Manual serialisation/deserialisation methods.
Implement classes with complex types such as lists and maps to be dynamic, enabling (all be it limited) automatic serialisation/deserialisation.
Your question does not specify how exactly dynamicTypes is built, or how its key is derived. So there is perhaps a detail to this that is not clear to me.
But what about something like this?
class Caster<T> {
final T Function(String) fromString;
Caster(this.fromString);
}
void main() {
Map<String, Caster> dynamicTypes = { "key": Caster<int>((s) => int.parse(s)) };
int v = dynamicTypes['key']!.fromString('1');
print(v);
}
Or, if you have the value as a dynamic rather than a string:
class Caster<T> {
T cast(dynamic value) => value as T;
}
void main() {
Map<String, Caster> dynamicTypes = { "key": Caster<int>() };
dynamic a = 1;
int v = dynamicTypes['key']!.cast(a);
print(v);
}
Or even more succinctly:
void main() {
dynamic a = 1;
int v = a;
print(v);
}

Can I pass a type of enum as an argument in Dart?

I want to have a method that takes a parameter of type enum as a parameter and then operates on it to get all possible values of the enum type, and do some work with each of those values.
I'd be hoping for something like:
Widget foo (EnumType enumType) {
for(var value in enumType.values) {
print(value.name);
}
}
I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a parm, however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error Error: The getter 'name' isn't defined for the class 'Object'.
Maybe my only problem is that I don't know how to specify a variable as an EnumType but I haven't been able to find a correct type for this.
EnumType.values is the equivalent of an automatically generated static method on EnumType and as such is not part of any object's interface. You therefore will not be able to directly call .values dynamically.
I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a [parameter], however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error
You can use a generic function that restricts its type parameter to be an Enum:
enum Direction {
north,
east,
south,
west,
}
List<String> getNames<T extends Enum>(List<T> enumValues) =>
[for (var e in enumValues) e.name];
void main() {
print(getNames(Direction.values)); // Prints: [north, east, south, west]
}
The problem with enums is that they can't be passed as a parameter, what you can do instead is that pass all the values and then extract the name from the toString method.
void printEnumValues<T>(List<T> values){
for(var value in values){
final name = value.toString().split('.')[1];
print(name);
}
}
Also I would recommend you look into freezed union classes as that might allow you an alternative approach towards the problem you're trying to solve.

Dart Language Extension Method

I am reading extension method in dart official documentation, and reached the bottom of the document. Here, the documentation mentioned the line List<T> operator -() => reversed.toList(); as a extension method on List<T>.
Here is the complete code.
extension MyFancyList<T> on List<T> {
int get doubleLength => length * 2;
List<T> operator -() => reversed.toList();
List<List<T>> split(int at) => [sublist(0, at), sublist(at)];
}
What does mean operator -(), operator +(List<T> t),and operator *(List<T> t) and how can I use these as extension method on List?
It means you can actually use it as an operator on the list. For example:
final list = [1,2,3,4,5];
print(-list);
prints [5,4,3,2,1]
Personally, I would not implement a revers like this. I think it would be quite unclear for other developers, while the reversed method is very clear on what it does. However, I understand it is just an example on how to define an operator in an extension.
operator +(List<T> t) and operator *(List<T> t) is between two lists. For example:
final a = [1,2];
final b = [3,4];
print(a + b);
prints [1,2,3,4]

how to handle empty array for text widget in build method?

How would I handle the objectA[0].name (a string) in the build method if the array is empty?
Text(objectB.objectC.objectA[0].name),
Assuming the array is objectC you can do something like:
Text(objectC.isEmpty? "" :objectC[0].name)
You can read more about ternary operators in dart here
There isn't a great way to do this inline but with a simple extension method to return the original null or the iterable depending on whether the item is null or empty you can make it work.
First
Extension Method
(requires dart v2.7 - update in your pubspec.yaml file)
extension IterableExtension<T> on Iterable<T> {
Iterable<T> get nullWhenEmpty =>
this == null || this.isEmpty ? null : this;
}
Second
To handle null values while you're traversing an object you can use the Dart's conditional member access operator (?.). This operator will only continue with the right-hand side if the left-hand side of the operator is not null. Use the elementAt method on a an iterable to be able to use the ?. operator in the chain. Then, use the ?. operations with the if null operator (??) to get your default value.
Solution
final String value = objectB?.objectC?.objectA?.nullWhenEmpty?.elementAt(0)?.name;
Text(value ?? 'Default Text');
You can, of course, inline the above code instead of using an additional variable.
Resources
Dart Language Tour: Other Operators
Dart Language Tour: Classes
Maybe checking if the list has an element, using isNotEmpty
child: (objectB.objectC.objectA.isNotEmpty)
? Text(objectB.objectC.objectA[0].name)
: Container(),

Multi if statement in class parameters setting

I know that in the latest version of dart we can use if else statements inside the build method. Does anyone know if we can use also if else statement when we setting class parameters? I know I can do inline statement there but inline is a bit hard to read when there are multiple conditions
const int i = 0;
class Person {
// NewClass n = NewClass(a: i == 0 ? 'a' : 'b'); //<- inline statement working
NewClass n = NewClass(a: if(i == 0) 'a' else 'b'); //<- if statement doesn't
}
class NewClass {
final String a;
const NewClass({this.a});
}
Edit:
Basically in my case I've got an TextField widget where I set its's type parameter from enum (Type.text, Type.numeric...) According to this parameter I want to set The textField parameters (textCapitalization, maxLength and so on)
As per your comment, you are already creating an enum for specifying the type of the fields.
enum Type {text, numeric}
Now for specifying the properties of that particular type, you can add an extension on this enum, as shown below:
extension TextFieldProperties on Type {
int get maxLength {
if (this == Type.text) {
return 10;
}
return 12;
}
}
So in your field class you already have a type defined, you can use that type variable to get the properties of that particular type of field.
Type type = Type.text;
print(type.maxLength); // Will print 10
type = Type.numeric;
print(type.maxLength); // Will print 12
Note: It will work only in Dart 2.7 and above
You want the conditional expression (?:), not the conditional statement or literal entry (if), as you have already discovered.
The reason if doesn't work is that if only works as a statement or as a collection literal entry. It doesn't work in arbitrary expressions.
The reason for the distinction is that the if syntax allows you to omit the else branch. That only makes sense in places where "nothing" is a valid alternative. For a statement, "doing nothing" is fine. For a collection, "adding nothing" is also fine.
In an expression context, you must evaluate to a value or throw. There is no reasonable default that we can use instead of "nothing", so an if is not allowed instead of an expression.
Doesn't work because this syntax doesn't exist in Dart. The only way to do what you would like to do is to use the ternary operator.
If you try it in the DartPad you will get an error.
I suggest you to use a function to return the right value.