Unable to use generic function in a generic function - flutter

I have the following class in my code
abstract class DatabaseKey<T> implements Built<DatabaseKey<T>, DatabaseKeyBuilder<T>> {
DatabaseKey._();
factory DatabaseKey([void Function(DatabaseKeyBuilder<T>) updates]) = _$DatabaseKey<T>;
String get name;
}
Then, I define the following generic typedef function:
typedef ObserveDatabaseEntity = Observable<DatabaseEntity<T>> Function<T>(DatabaseKey<T> key);
But, when I try to use it as follows, the code has an error.
static ObserveConfigurationValue observe(
GetConfigurationState getState,
ObserveDatabaseEntity observeDatabaseEntity,
) {
assert(getState != null);
assert(observeDatabaseEntity != null);
return <KT>(ConfigKey<KT> key) {
return Observable.just(getState())
.flatMap((state) {
final dbKey = _databaseKeyFromConfig<KT>(key);
return observeDatabaseEntity(dbKey)
.map(_configValueFromDatabaseEntity);
});
}
}
DatabaseKey<T> _databaseKeyFromConfig<T>(ConfigKey<T> key) {
return DatabaseKey((build) => build
..name = key.value,
);
}
The error I am getting is:
The argument type DatabaseKey can't be assigned to the parameter DatabaseKey.
I see nothing wrong with this code or why it shouldn't work, but maybe my understanding of what can be written in Dart is wrong. What would be the correct way to write this, if possible at all?
EDIT#1:
Note:
The typedef ObserveDatabaseEntity is in one file
The static ObserveConfigurationValue observe(GetConfigurationState getState, ObserveDatabaseEntity observeDatabaseEntity) is is another file
From playing around, it seems that placing them in a single file, the error disappears.
Still, I believe that this should work in separate files as well,

This error looks like an import mismatch.
In dart, you can import file either through relative path or package.
import 'lib/some_file.dart'; //relative
import 'package:myapp/lib/some_file.dart'; //package
There's really no better way but once you choose one, you have to stick to it. If you don't (meaning you have imported a file using a package import and the same file elsewhere with a relative path) Dart will place them in two different namespaces and think they are two different classes.

Related

A way to read a String as dart code inside flutter?

I want to build a method to dynamically save attributes on a specific object
given the attribute name and the value to save I call the "save()" function to update the global targetObj
var targetObj = targetClass();
save(String attribute, String value){
targetObj.attribute = value;
print(targetObj.attribute);
}
But I'm getting the following error:
Class 'targetClass' has no instance setter 'attribute='.
Receiver: Instance of 'targetClass'
Tried calling: attribute="Foo"
The only thing that I can think of is that "attribute" due to being type String results in an error.
That lead me to think if there is a way to read a String as code, something like eval for php.
As #Randal mentioned, you cannot create class..method at runtime. Still, you can try something like this.
A certain class
class Foo {
dynamic bar1;
dynamic bar2;
// ...
}
Your save method
save(Foo fooObject, String attribute, dynamic value) {
if ("bar1" == attribute) fooObject.bar1 = value;
else if ("bar2" == attribute) fooObject.bar2 == value;
// ...
}
Dart (and thus flutter) does not have a way to compile and execute code at runtime (other than dart:mirrors, which is deprecated). You can build additional code that derives from other code using the various builder mechanisms, although it can be rather complicated to implement (and use!).

Import extension method from another file in Dart

With Dart 2.6, I can use extension methods like this :
extension on int {
int giveMeFive() {
return 5;
}
}
main(List<String> arguments) async {
int x;
x.giveMeFive();
}
Everything works perfectly ! :D
But now if I want to put my extension method in another file like this :
main.dart
import 'package:untitled5/Classes/ExtendInt.dart';
main(List<String> arguments) async {
int x;
x.giveMeFive();
}
ExtendInt.dart
extension on int {
int giveMeFive() {return 5;}
}
It fails with a depressing error ..
bin/main.dart:9:5: Error: The method 'giveMeFive' isn't defined for the class 'int'.
Try correcting the name to the name of an existing method, or defining a method named 'giveMeFive'.
x.giveMeFive();
^^^^^^^^^^
Is it not allowed to do that or am I doing something wrong ?
Thanks for reading ! :)
This is working as intended. An extension with no name is implicitly given a fresh name, but it is private. So if you want to use an extension outside the library where it is declared you need to give it a name.
This is also helpful for users, because they may need to use its name in order to be able to resolve conflicts and explicitly ask for the extension method giveMeFive from your extension when there are multiple extensions offering a giveMeFive on the given receiver type.
So you need to do something like
extension MyExtension on int {
int giveMeFive() => 5;
}

Better way to do class type alias?

From time to time, I would like to call a class differently depending on the context or to reduce duplication.
Let's assume, I have the following classes defined:
// in file a.dart
class A {
final String someprop;
A(this.someprop)
}
// in file b.dart
abstract class BInterface {
String get someprop;
}
class B = A with EmptyMixin implements BInterface;
For this syntax to check out, I have to define EmptyMixin so that the syntax is OK.
Do you know of a better/prettier way to do this "aliasing" in Dart?
I'm afraid the way you're doing it is the prettiest way to do this at the moment. There is a very old, but still open and active issue: https://github.com/dart-lang/sdk/issues/2626 that proposes the typedef B = A; syntax for aliasing types.

Extending a class in another file

I have some TypeScript code that is being generated by a tool. I'd like to extend this class in another file. As of 0.9.1.1, what's the best way to go about this?
I thought maybe I could staple my additional functions onto the prototype, but this is giving various errors (which change depending what mood the compiler is in).
For example:
Foo.ts (generated by a tool)
module MyModule {
export class Dog { }
}
Bar.ts
module MyModule {
function bark(): string {return 'woof';}
Dog.prototype.bark = bark;
}
You cannot split a class definition between multiple files in TypeScript. However typescript understands how JavaScript works and will let you write idomatic JavaScript classes just fine:
module MyModule {
export function Dog(){};
}
module MyModule {
function bark(): string {return 'woof';}
Dog.prototype.bark = bark;
}
Try it online
One way around this is to use inheritance:
class BigDog extends Dog{
bark(){}
}
I have encountered your problem as well before, but I had some deeper problems. You can see from basarat's example, that simple functions can be added as an extension to the prototype, but when it comes to static functions, or other static values you might want to extend your (presumably third party) class, then the TSC will warn you, that there is no such method defined on the class statically.
My workaround was the following little hack:
module MyModule {
export function Dog(){};
}
// in the other file
if (typeof MyModule !== 'undefined'){
Cast<any>(MyModule.Dog).Create = ()=>{return new Dog();};
}
// where Cast is a hack, for TS to forcefully cast types :)
Cast<T>(element:any):T{ return element; }
This should cast MyModule.Dog, to an any object, therefore allowing attachment of any kinds of properties, functions.

Get type of class field with null value in Haxe

Is it possible to get class of field with null value in haxe?
The function "Type.getClass" gets class of value (setted at runtime), but I need to get class defined in a compilation-time.
Function "getClassFields" returns only names of fields, without classes.
For example:
class MyCls
{
public static var i:Int = null;
public static var s:String = null;
}
trace(Type.getClass(MyCls.i)); // show "null", but I need to get Int
trace(Type.getClass(MyCls.s)); // show "null", but I need to get String
And in my situation I can't to change sources of class MyCls.
Thanks.
You can try Runtime Type Information. It's a Haxe feature which allow go get full description of a type in runtime.
http://haxe.org/manual/cr-rtti.html
Since you need to get the types for null fields, you really need to resort to Haxe's Runtime Type Information (RTTI) (as #ReallylUniqueName recomended).
import haxe.rtti.Rtti;
import haxe.rtti.CType;
class Test {
static function main()
{
if (!Rtti.hasRtti(MyCls))
throw "Please add #:rtti to class";
var rtti = Rtti.getRtti(MyCls);
for (sf in rtti.statics)
trace(sf.name, sf.type, CTypeTools.toString(sf.type));
}
}
Now, obviously, there's a catch...
RTTI requires a #:rtti metadata, but you said you cannot change the MyCls class to add it. The solution then is do add it through a macro in your build file. For instance, if you're using a .hxml file, it should then look like:
--interp
--macro addMetadata("#:rtti", "MyCls")
-main Test
With this and your own MyCls definition, the output would look like:
Test.hx:11: i,CAbstract(Int,{ length => 0 }),Int
Test.hx:11: s,CClass(String,{ length => 0 }),String