I am working on a searching for an element. I am using AutoComplete widget where users can type and based on matched results it will show suggestions. My data is coming from Post requests. Earlier there was a Get request and AutoComplete suggestion was working for me but now it has been changed to Post request.
Due to this now I am getting this error Instance member 'res' can't be accessed using static access
This is my search_model.dart
SearchSquad searchSquadFromJson(String str) =>
SearchSquad.fromJson(json.decode(str));
String searchSquadToJson(SearchSquad data) => json.encode(data.toJson());
class SearchSquad {
SearchSquad({
required this.count,
required this.res,
});
int count;
List<Re> res;
factory SearchSquad.fromJson(Map<String, dynamic> json) => SearchSquad(
count: json["count"],
res: List<Re>.from(json["res"].map((x) => Re.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"count": count,
"res": List<dynamic>.from(res.map((x) => x.toJson())),
};
}
class Re {
Re({
required this.squadId,
required this.squadName,
required this.defaultProfileImageId,
required this.profimgid,
required this.profimgname,
required this.profimgurl,
required this.profimgrotation,
this.profimgposition1,
this.profimgposition2,
required this.profimgscale,
this.profimgrotationfocuspoint1,
this.profimgrotationfocuspoint2,
});
String squadId;
String squadName;
String defaultProfileImageId;
String profimgid;
String profimgname;
String profimgurl;
int profimgrotation;
dynamic profimgposition1;
dynamic profimgposition2;
double profimgscale;
dynamic profimgrotationfocuspoint1;
dynamic profimgrotationfocuspoint2;
change this
return SearchSquad.res
to
SearchSquad? searchSquad;//instance for the class
return searchSquad.res// change to this
I don't know where you called _getSearchSquad() function but you will get the point
SearchSquad? searchSquad; //instance for the class
void getSearch() async{
searchSquad = await _getSearchSquad(); //await it since its Future and put it in async function
}
return searchSquad.res// then use it in the return of AuthoComplete
Add a static key word before defining res static List<Re> res;
Related
I try to get data from api. CallListDto class is empty according to user type. So, sometime this class is empty sometimes it has data. I populate dropdown menu items with this class.
My problem is, when this class is empty i got error. How can i solve this.
My model class is below
Login loginFromJson(String str) => Login.fromJson(json.decode(str));
String loginToJson(Login data) => json.encode(data.toJson());
class Login {
Login({
required this.token,
required this.callListDto,
});
String token;
List<CallListDto> callListDto;
factory Login.fromJson(Map<String, dynamic> json) => Login(
token: json["token"],
callListDto: List<CallListDto>.from(
json["callListDto"].map((x) => CallListDto.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"token": token,
"callListDto": List<dynamic>.from(callListDto.map((x) => x.toJson())),
};
}
class CallListDto {
CallListDto({
required this.callId,
required this.stationCode,
required this.callType,
});
int callId;
String stationCode;
int callType;
factory CallListDto.fromJson(Map<String, dynamic> json) => CallListDto(
callId: json["callID"],
stationCode: json["stationCode"],
callType: json["callType"],
);
Map<String, dynamic> toJson() => {
"callID": callId,
"stationCode": stationCode,
"callType": callType,
};
}
Before calling the model class check that str is not empty, for example
if (dataObject.isEmpty) return;
I am getting following errors:
Instance members can't be accessed from a factory constructor. (Documentation) Try removing the reference to the instance member.
The argument type 'List<Map<String, dynamic>>?' can't be assigned to the parameter type 'List<Vaccination>'. (Documentation)
at line _convertVaccinations(json['vaccinations'] as List<dynamic>));
Code:
final String name;
final String? notes;
final String type;
final List<Vaccination> vaccination;
final String? referenceId;
Pet(this.name, {this.notes, required this.type, required this.vaccination, this.referenceId});
factory Pet.fromJson(Map<String, dynamic> json) =>
Pet(
json['name'] as String,
notes: json['notes'] as String,
type: json['types'] as String,
referenceId: json['referenceId'] as String,
vaccination:
_convertVaccinations(json['vaccinations'] as List<dynamic>));
List<Map<String, dynamic>>? _convertVaccinations(List<dynamic>? vaccinations) {
if (vaccinations == null) {
return null;
} else {
final vaccinationMap = <Map<String, dynamic>>[];
for (var element in vaccinations) {
vaccinationMap.add(element.toJson);
}
return vaccinationMap;
}
}
Factory and instance member error:
Well it is because factory Pet.fromJson(...) is a factory constructor, and the class method _convertVaccinations(...) is an instance member.
If you make _convertVaccinations(...) static, it will accept the use of it in the factory constructor.
Argument error:
vaccination is of type List<Vaccination> and the method _convertVaccination(...) returns either null or List<Map<String, dynamic>>
In other words, you cannot assign null to List<T> unless it says List<T>? and the class Vaccination is not a Map<String, dynamic>
Maybe you want to do something like final List<Vaccination>? vaccinations; OR return <Vaccination>[] instead of null if vaccinations == null.
So you'd probably want to do write _convertVaccinations(...) as:
static List<Vaccination>? _convertVaccination(List<dynamic>? vaccinations) {
return vaccinations?.map((e) => Vaccination.fromJson(e as Map<String,dynamic>).toList();
}
or:
static List<Vaccination> _convertVaccination(List<dynamic>? vaccinations) {
return vaccinations?.map((e) => Vaccination.fromJson(e as Map<String,dynamic>).toList() ?? <Vaccination>[];
}
Side note: Maybe you have more methods that you haven't presented here. Because it looks a bit wonky when your Pet.fromJson(...) use a element.toJson down the call stack.
I am learning flutter, trying to use Getx's GetConnect Custom configuration,
when try to set defaultDecoder for default request, it complains:
The getter 'fromJson' isn't defined for the type 'Resp'.
Try importing the library that defines 'fromJson', correcting the name to the name of an existing getter, or defining a getter or field named 'fromJson'.dart"
How to fix this error?
Here is My Code:
import 'package:get/get.dart';
class AuthService extends GetConnect {
#override
void onInit() {
// All request will pass to jsonEncode so CasesModel.fromJson()
httpClient.defaultDecoder = Resp.fromJson;
httpClient.baseUrl = 'http://localhost/app_api/auth';
}
Future<Response<Map<String, dynamic>>> getCaptcha(String mobile) =>
get("get_captcha");
}
class Resp {
final int Errcode;
final String Errmsg;
final Map<String, dynamic> Data;
Resp(this.Errcode, this.Errmsg, this.Data);
factory Resp.fromJson(Map<String, dynamic> json) {
return Resp(json["errcode"], json["errmsg"], json["data"]);
}
}
Check this
https://gist.github.com/eduardoflorence/d918d05ad71175b52c2aca95588c305d
class CityModel {
CityModel({
required this.abbreviation,
required this.name,
});
String abbreviation;
String name;
factory CityModel.fromJson(Map<String, dynamic> json) => CityModel(
abbreviation: json["sigla"],
name: json["nome"],
);
static List<CityModel> listFromJson(list) => List<CityModel>.from(list.map((x) => CityModel.fromJson(x)));
}
and Then
httpClient.defaultDecoder = CityModel.listFromJson;
I have this class to deserialize a paginated response from a server:
class PaginatedResponse {
final int current_page;
final dynamic data;
final String first_page_url;
final int from;
final int last_page;
final String last_page_url;
final String next_page_url;
final String path;
final int per_page;
final String prev_page_url;
final int to;
final int total;
PaginatedResponse({
this.current_page,
this.data,
this.first_page_url,
this.from,
this.last_page,
this.last_page_url,
this.next_page_url,
this.path,
this.per_page,
this.prev_page_url,
this.to,
this.total,
});
factory PaginatedResponse.fromJson(Map<String, dynamic> json) {
return json == null
? null
: PaginatedResponse(
current_page: json['current_page'],
data: json['data'],
first_page_url: json['first_page_url'],
from: json['from'],
last_page: json['last_page'],
last_page_url: json['last_page_url'],
next_page_url: json['next_page_url'],
path: json['path'],
per_page: json['per_page'],
prev_page_url: json['prev_page_url'],
to: json['to'],
total: json['total'],
);
}
Map<String, dynamic> toJson() => {
'current_page': current_page,
'data': data,
'first_page_url': first_page_url,
'from': from,
'last_page': last_page,
'last_page_url': last_page_url,
'next_page_url': next_page_url,
'path': path,
'per_page': per_page,
'prev_page_url': prev_page_url,
'to': to,
'total': total,
};
}
That same response is used for multiple different methods that expect different Types on the data property.
It would be ideal if I don't have to repeat all the other properties just to change the data type.
So how would I go about extending this class to allow for subclasses of this to have their proper Type in data?
Thank you!
To achieve that, you need to make PaginatedResponse with generic type of data. Like this:
class PaginatedResponse<DATA> {
final int current_page;
final DATA data;
...
The most difficult part is serialization/deserialization support of this by JSON frameworks. To me the best support of generics is implemented in built_value package. See here for complete example
I need to add the value in the list which is comma separated.
Sample data:
English,Hindi,French
Below is the class of List:
class LanguageService {
}
class Language extends Taggable {
final String name;
/// Creates Language
Language({
this.name,
// this.position,
});
#override
List<Object> get props => [name];
/// Converts the class to json string.
String toJson() => ''' {
"name": $name,\n
}''';
//}
String thuJson() => ''' {
"name": $name,
}''';
}
GetTags getTagsFromJson(String str) => GetTags.fromJson(json.decode(str));
class GetTags {
List<Content> content;
bool success;
//String error;
GetTags({
this.content,
this.success,
});
factory GetTags.fromJson(Map<String, dynamic> json) => GetTags(
content: (json["content"] as List).map((x) => Content.fromJson(x)).toList(),
success: json["success"],
);
}
class Content {
String tagname;
Content({
this.tagname,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
tagname: json == null ? 'Empty' : json["tagname"]
);
}
I tried split but it is giving me error.
List<Language> _selectedLanguages;
_selectedLanguages = [];
//responseBody['user_lang'] = 'English,Hindi,French' Data looks like this
_selectedLanguages = responseBody['user_lang'].split(', ');
Exception Caught: type 'List<String>' is not a subtype of type 'List<Language>'
Also tried.
_selectedLanguages.add(responseBody['user_lang']);
Exception Caught: type 'String' is not a subtype of type 'Language'
Update
I tried this too but getting error.
List _dbLanguages = responseBody['user_lang'].split(', ');
selectedLanguages = _dbLanguages.map<List<Language>>((item) => Language(item))
A value of type 'Iterable<List<Language>>' can't be assigned to a variable of type 'List<Language>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Language>'.
One way you can do this is like this.
List<Language> _selectedLanguages;
_selectedLanguages = (responseBody['user_lang'].split(',') as List<String>).map((text) => Language(name: text)).toList();
Dart has a very good type checking system and I think your problem is an obvious one based on the error message. You must convert your list of String into a list of Language. I don't recall the syntax from the top of my head but I think you should be able to convert your list of String with .map<List<Language>>((item) => Language(item))