I have a function Future<T?> getDocById<T>(String id) aysnc {}
, it gets the data from web and return the value with type T
. How can I convert any incoming data from web to a given type?
use case - class User{ String name; User(this.name);}
class User{ String name; User(this.name);}
now, await getDocById<User>()
how can I convert the data to type User inside getDocById
function? in another case - getDocById<Boo>
it should get data from web and convert it to Boo and return
Since I just answered a similar question I am copying the code into here. However, if you have an unknown T
incoming, you need to distinguish cases based on what is incoming. Without this you want be able to convert a bool
or int into
a String name
.
Create a method in one of the classes
class A {
A(this.a);
final int a;
B toB() {
return B(
b: a,
}
}
class B {
B(this.b);
final int b;
}
To be used like final bInstance = aInstance.toB();
meaning you declared somewhere aInstance = A(1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.