Add comma separated value to class list - flutter

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))

Related

Error: Instance member 'res' can't be accessed using static access

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;

Conversion error from object to json and back in flutter

I am trying to convert a list of objects as a json string in shared preferences.
Object class
SuggestionModel suggestionModelFromJson(String str) =>
SuggestionModel.fromJson(json.decode(str));
String suggestionModelToJson(SuggestionModel data) =>
json.encode(data.toJson());
class SuggestionModel {
SuggestionModel({
this.category,
this.icon,
this.subs,
});
eCategory? category;
IconData? icon;
List<Sub>? subs;
factory SuggestionModel.fromJson(Map<String, dynamic> json) =>
SuggestionModel(
category: json["category"],
icon: json["icon"],
subs: List<Sub>.from(json["subs"].map((x) => Sub.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"icon": icon,
"subs": List<dynamic>.from(subs!.map((x) => x.toJson())),
};
}
class Sub {
Sub({
this.subCategory,
this.values,
});
String? subCategory;
List<Value>? values;
factory Sub.fromJson(Map<String, dynamic> json) => Sub(
subCategory: json["sub_category"],
values: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sub_category": subCategory,
"values": List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
class Value {
Value({
this.subName,
this.selected,
});
String? subName;
bool? selected;
factory Value.fromJson(Map<String, dynamic> json) => Value(
subName: json["sub_name"],
selected: json["selected"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"selected": selected,
};
}
When I try to do
List<SuggestionModel> list;
String encodedData = jsonEncode(list);
it gives me an error
Converting object to an encodable object failed: Instance of 'SuggestionModel'
Im not following where the exact issue comes from. tried debugging and still no luck
How can I rectify this?
Update. I've changed the enum to a String and removed the IconData field. And the above issue had resolved.
Now when I try to get the saved Json string and convert that back to list of objects. I get an error
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<SuggestionModel>'
at this line
var t = await _dataManager.getSelectedList(s);
var addedObj = json.decode(json.decode(t!));
//here...
var list = addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
Try this:
String encodedData = jsonEncode(list.map((e) => e.toJson()).toList());
So the first thing was to update the enum property of Model class to String and remove IconData.
Then for the second issue.
update the decoding function like
List<SuggestionModel> list =
addedObj.map((e) => SuggestionModel.fromJson(e)).toList();

Error listing information from an API (Expected a value of type 'int', but got one of type 'String')

I'm getting information from a REST API, but when displaying the information I get the error:
Error: Exception: Expected a value of type 'int', but got one of type 'String'
This is my get method:
Future<List<Requests>> searchRequests() async {
try {
final response = await http.get(
Uri.parse(BaseUrl.baseUrl + 'api/search'));
if (response.statusCode == 200) {
List<Requests> list = parseRequests(response.body);
return list;
} else {
throw Exception("Error");
}
} catch (e) {
throw Exception(e.toString());
}
}
static List<Requests> parseRequests(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed
.map<Requests>((json) => Requests.fromJson(json))
.toList();
}
and defined my model like this:
import 'package:flutter_gentelella/models/usuario.dart';
class Requests {
final String id;
final String data1;
final String data2;
final int data3;
const Requests({
required this.id,
required this.data1,
required this.data2,
required this.data3,
});
factory Requests.fromJson(Map<String, dynamic> json) {
return Solicitacoes(
id: json['_id'],
data1: json['data1'],
data2: json['data2'],
data3: json['user']['data3']);
}
Map<String, dynamic> toJson() => {
'_id': id,
'data1': data1,
'data2': data2,
'data3': data3,
};
}
At what point in the code do I convert to int?
I'm trying to generate the order list on the screen but I get the error reported above. I appreciate if someone helps me analyze!
I'd say that the problem is with the field data3: it's the only thing I see in your code defined as an int, and the error is telling you that something was expected as int but it came up as String.
Something like this shouls work (just handle the case in which data3 is not a number appropriately):
factory Requests.fromJson(Map<String, dynamic> json) {
return Solicitacoes(
id: json['_id'],
data1: json['data1'],
data2: json['data2'],
data3: int.tryParse(json['user']['data3']) ?? 'Not a number');
}

Why am I getting a _TypeError when trying to create a list?

I have the following JSON that is getting returned from an API call:
{
"categories": {
"mortgage": "Mortgage",
"haircutsClothing": "Haircuts & Clothing",
"homeRepairMaintenance": "Home Repair & Maintenance"
},
"other": {...}
}
And then I have this class acting as a model for the JSON data:
class APIData {
final Map<String, dynamic> parsedJson;
APIData({required this.parsedJson});
factory APIData.fromJson(Map<String, dynamic> parsedJson) {
List<Category> categories = parsedJson['categories']
.map((i) => Category.fromJson(i))
.toList();
return APIData(parsedJson: parsedJson);
}
}
class Category {
final String key;
final String category;
Category({required this.key, required this.category});
factory Category.fromJson(Map<String, dynamic> parsedJson) {
return Category(key: parsedJson['key'], category: parsedJson['value']);
}
}
When I run that, I get this error:
_TypeError (type '(dynamic) => Category' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')
What am I doing wrong that is causing this error?
method .map on Map object has to return Map object too.
try this
final categoriesMap = parsedJson['categories'] as Map;
final List<Category> categories =
categoriesMap.entries
.map((e) => Category(key: e.key, category: e.value))
.toList();
entries from a Map returns an Iterable of Map Entry. then you can iterate through it and use key and value properties.

Fauna DB and flutter, unable to get a default value on Select using the faunadb_http package

I am using the faunadb_http package and I want the value to be returned null from Fauna DB if the field does not exist in the collection. I am just not able to figure out what should I put in the default parameter of this package so that I get that back as the default value.
I tried the following two variations of default parameter and I get "Value not found at path" error for first and just an empty Object {} for second.
'itemPrice': Select(["data", "itemPrice"], Var("postDoc"), default_: null),
'itemLocation': Select(["data", "itemLocation"], Var("postDoc"), default_: Obj({})),
Can somebody help me understand what should I be passing to default_ so that I get a String or Int as a response back.
This is the code for the Select class from the package
#JsonSerializable()
class Select extends Expr {
#JsonKey(name: 'select')
final Object path;
final Expr from;
#JsonKey(name: 'default', disallowNullValue: true, includeIfNull: false)
final Expr? default_;
Select(this.path, this.from, {this.default_});
factory Select.fromJson(Map<String, dynamic> json) => _$SelectFromJson(json);
#override
Map<String, dynamic> toJson() => _$SelectToJson(this);
}
And this is for the Expr class
class Expr {
static Object? wrap_value(dynamic value) {
if (value is List) {
return wrap_values(value);
} else if (value is Map<String, dynamic>) {
return Obj(value);
} else if (value is DateTime) {
return Time(value.toUtc().toIso8601String());
} else {
return value;
}
}
static Object? wrap_values(Object? data) {
if (data == null) return null;
if (data is List) {
return List.generate(
data.length,
(e) => wrap_value(data[e]),
growable: false,
);
} else if (data is Map<String, dynamic>) {
return data.map(
(key, value) => MapEntry(key, wrap_value(value)),
);
}
return data;
}
Expr();
factory Expr.fromJson(Map<String, dynamic> json) => _$ExprFromJson(json);
Map<String, dynamic> toJson() => _$ExprToJson(this);
#override
String toString() {
return json.encode(this).toString();
}
}
I'm going to set aside the language-specific aspects, as I'm not familiar with Dart.
That said, as I read through your post it seems like Select() is working as defined. The third argument is what is returned if your data is not found, e.g., null.
In the first case, you are returning null explicitly, and Fauna removes keys with null values, so that value would indeed not be found.
In the second case, you are returning an empty Object, and you receive an empty Object, so that seems to be working as defined as well.
Can somebody help me understand what should I be passing to default_ so that I get a String or Int as a response back.
In this case you need to explicitly set an Expr that will evaluate to a string or Int. If the empty string "" and zero 0 are reasonable defaults, then you would want:
'itemPrice': Select(["data", "itemPrice"], Var("postDoc"), default_: 0),
and
'itemLocation': Select(["data", "itemLocation"], Var("postDoc"), default_: ""),
I got in touch with the author of the package and they were kind enough to fix the issue within a day of reporting it. Now it works as expected.