I want to create a data class and put some attributes in my data class.
here is my code:
import 'dart:ffi';
class UserDetail {
final Long id;
final String name;
final String phone;
final String creditCardNumber;
final String nationalId;
final Int score;
UserDetail(this.id, this.name, this.phone, this.creditCardNumber,
this.nationalId, this.score);
factory UserDetail.fromJson(Map<String, dynamic> json) {
return UserDetail(
json['id'],
json['name'],
json['phone'],
json['creditCardNumber'],
json['nationalId'],
json['score']
);
}
}
the problem is when I want to run the project I get this error:
lib/domain/UserDetail.dart:1:8: Error: Not found: 'dart:ffi'
import 'dart:ffi';
^
lib/domain/UserDetail.dart:5:9: Error: Type 'Long' not found.
final Long id;
^^^^
lib/domain/UserDetail.dart:10:9: Error: Type 'Int' not found.
final Int score;
^^^
lib/domain/UserDetail.dart:5:9: Error: 'Long' isn't a type.
final Long id;
^^^^
lib/domain/UserDetail.dart:10:9: Error: 'Int' isn't a type.
final Int score;
^^^
Failed to compile application.
I don't understand why Int is not a type! and how can I solve this problem?
Just remove import dart:ffi; import, also Long and Int are not valid data types in Dart, use int instead of them
class UserDetail {
final int id;
final String name;
final String phone;
final String creditCardNumber;
final String nationalId;
final int score;
UserDetail(this.id, this.name, this.phone, this.creditCardNumber, this.nationalId, this.score);
factory UserDetail.fromJson(Map<String, dynamic> json) {
return UserDetail(
json['id'],
json['name'],
json['phone'],
json['creditCardNumber'],
json['nationalId'],
json['score']
);
}
}
Related
I am new in Dart(OOP Languange) which it is a bit similar in Java
But this code get me confusion
What is the purpose of colon(:) before the super keyword within SchoolID class that has been inherit with Person class?
Here is the code:
class Person {
String name;
int age;
int height;
Person({this.name, this.age, this.height});
}
class SchoolID extends Person {
int id;
int year;
String name;
SchoolID({this.id, this.year, this.name}) : super(name: name);
}
Another Example ,,, focus on colon the fishmap
AllFish.fromJson(Map<String, dynamic> json)
: fishMap = json.map(
(String k, dynamic v) => MapEntry(
k,
Fish.fromJson(v),
),
);
It's considered as an initializer list which runs before the constructor body, here you're calling the super that means the constructor of your Person class.
It's an initializer. This means the initializer is executed before the constructor body
I've been trying to figure out how to use a named constructor to construct super and sub classes from JSON. Below is my example with some notes on what I've tried in the fromJson method body. Can anyone point me in the right direction? Thanks!
class Item {
final String name;
final int id;
final String image;
final double price;
final bool available;
Item(this.name, this.id, this.image, this.price, this.available);
Item.fromJson(Map<String, dynamic> json)
: name = json['name'],
id = json['id'],
image = json['image'],
price = json['price'],
available = json['available'];
}
class CartItem extends Item {
final int quantity;
CartItem({
#required this.quantity,
#required name,
#required id,
#required price,
#required image,
#required available
}): super(id, name, image, price, available)
CartItem.fromJson(Map<String, dynamic> json)
: quantity = json['quantity'],
// for whatever ever reason, super here seems to refer to CartItem
// so this doesn't work
super.name = json['name'],
// calling 'name' without the super doesn't work either
name = json['name']
}
You should use a the super's fromJson constructor in the child class's fromJson constructor. You can pass the Map in the child directly to the super without issues. Ex:
CartItem.fromJson(Map<String, dynamic> json)
: quantity = json['quantity'],
super.fromJson(json);
How do I do something like this (getNames)?
class APIServer {
String name;
Future<String> getNames(String query);
APIServer({this.name, this.function});
}
You need to use the Function type to declare a function variable.
class APIServer {
String name;
Future<String> Function(String query) getNames;
APIServer({this.name, this.getNames});
}
Alternatively, create a typedef signature to tie the function signature to a data type:
typedef NameGetter = Future<String> Function(String query);
class APIServer {
String name;
NameGetter getNames;
APIServer({this.name, this.getNames});
}
I am new to flutter and getting type error. I am trying to use json automated serializations.
AFTER DOING SOME TWEAKS HERE IS HOW IT LOOKS LIKE
Here is how I am trying to get the data from api
Future getMyProduct() async {
final res = await http.get('url');
final data = json.decode(res.body);
BaseResponse req = new BaseResponse.fromJson(data);
return req;
}
My BaseResponse class looks like this
import 'package:dynamicapp/model/model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'response.g.dart';
#JsonSerializable()
class BaseResponse extends Object {
final int id;
final int sellingPrice;
final int totalStock;
final String productName;
final String productDesc;
final List<Image> images;
BaseResponse(this.id, this.sellingPrice, this.totalStock, this.productName,
this.productDesc, this.images);
factory BaseResponse.fromJson(Map<String, dynamic> json) => _$BaseResponseFromJson(json);
Map<String, dynamic> toJson() => _$BaseResponseToJson(this);
}
#JsonSerializable()
class Image extends Object {
final int id;
final String image;
// final int product_id;
Image(this.id, this.image);
factory Image.fromJson(Map<String, dynamic> json) => _$ImageFromJson(json);
Map<String, dynamic> toJson() => _$ImageToJson(this);
}
Could anyone please help me with this. I am stuck here. Have been trying different methods but none working. Thank you.
It looks like data is a List<dynamic>, then data.map(someFunc).toList() will take each element of data pass it to someFunc and form it back into a list of the return type of someFunc (which you will presumably want to be BaseResponse). Which tells you that someFunc needs to be a function that takes dynamic and returns BaseResponse.
You'd want to write something like this:
final data = json.decode(res.body);
List<BaseResponse> responses =
data.map((j) => BaseResponse.fromJson(j)).toList();
all my JSON data contains status(int), msg(String), and data(any Type). Because I'm come from java ,I want use generics。I'm writing a deserialize for a top generics with built_value, but failed.
I have try this
https://github.com/google/built_value.dart/blob/master/end_to_end_test/test/generics_serializer_test.dart.
But do not really understand.
There follows my code:
abstract class GenericValue<T>
implements Built<GenericValue<T>, GenericValueBuilder<T>> {
T get data;
int get status;
String get msg;
GenericValue._();
static Serializer<GenericValue> get serializer => _$genericValueSerializer;
factory GenericValue([updates(GenericValueBuilder<T> b)]) =
_$GenericValue<T>;
}
abstract class UserInfo implements Built<UserInfo, UserInfoBuilder> {
static Serializer<UserInfo> get serializer => _$userInfoSerializer;
String get id;
String get email;
UserInfo._();
factory UserInfo([updates(UserInfoBuilder b)]) = _$UserInfo;
}
GenericValue<UserInfo> parseUserInfo(String jsonStr) {
final parsed = json.jsonDecode(jsonStr);
final specifiedType = const FullType(GenericValue, [FullType(UserInfo)]);
final serializersWithBuilder = (standardSerializers.toBuilder()
..addBuilderFac`enter code here`tory(specifiedType, () => GenericValueBuilder<UserInfo>
()))
.build();
Response<UserInfo> response = serializersWithBuilder.deserialize(parsed,
specifiedType: specifiedType);
return response;
}
but result is: Invalid argument(s): Unknown type on deserialization. Need either specifiedType or discriminator field.
how can it do it in right way, to deserialize JSON data like this.
String toJsonUserInfo() {
final specifiedType = const FullType(GenericValue, [FullType(UserInfo)]);
final serializersWithBuilder = (standardSerializers.toBuilder()
..addBuilderFactory(
specifiedType, () => GenericValueBuilder<UserInfo>()))
.build();
return json.encode(
serializersWithBuilder.serialize(this, specifiedType: specifiedType));
}
static GenericValue<UserInfo> fromJsonUserInfo(String jsonString) {
final specifiedType = const FullType(GenericValue, [FullType(UserInfo)]);
final serializersWithBuilder = (standardSerializers.toBuilder()
..addBuilderFactory(
specifiedType, () => GenericValueBuilder<UserInfo>()))
.build();
return serializersWithBuilder.deserialize(json.decode(jsonString),
specifiedType: specifiedType);
}
it works.