Hoping for some help on this error please. I am getting an Error when I try to run my Autofill suggestions. I have three print statements to check how far the code is getting. I get the 'working?222' print but it doesn't make it to the 'did I get here' print statement. I receive the following error. The Error I'm getting is a Type Error which I haven't been able to fix. Error: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'. I know it's a type mismatch but I have been unsuccessful in fixing it. Here is my code where it fails.
import 'dart:convert';
import 'package:http/http.dart' as http;
class SugCompound {
final String compound;
const SugCompound({
required this.compound,
});
static SugCompound fromJson(Map<String, dynamic> json) => SugCompound(
compound: json['compound'],
);
}
class SugCompoundApi {
static Future<List<SugCompound>> getSugCompoundSuggestions(String query) async {
// print('working?');
final url = Uri.parse(
'https://website.com/rest/autocomplete/compound/$query/json?limit=6');
final response = await http.get(url);
print('working?222');
if (response.statusCode == 200) {
final List sugCompounds = json.decode(response.body);
print('did I get here');
return sugCompounds.map((json) =>
SugCompound.fromJson(json)).where((sugCompound) {
final compoundLower = sugCompound.compound.toLowerCase();
final queryLower = query.toLowerCase();
return compoundLower.contains(queryLower);
}).toList();
} else {
throw Exception();
// }
}
}
}
json looks like this:
{
"status": {
"code": 0
},
"total": 6,
"dictionary_terms": {
"compound": [
"aspirin",
"Aspirina",
"AspirinTest2",
"ASPIRIN (MART.)",
"ASPIRIN COMPONENT OF AXOTAL",
"ASPIRIN COMPONENT OF AZDONE"
]
}
}
error is where you are assigning a map to list:
final List sugCompounds = json.decode(response.body);
which is now allowed, you can Change your class like:
class SugCompound {
final List<String> compound;
const SugCompound({
required this.compound,
});
static SugCompound fromJson(Map<String, dynamic> json) => SugCompound(
compound: json['dictionary_terms']['compound'],
);
}
And your future will be like:
Future<List> getSugCompoundSuggestions(String query) async {
// print('working?');
final url = Uri.parse(
'https://website.com/rest/autocomplete/compound/$query/json?limit=6');
final response = await http.get(url);
if (response.statusCode == 200) {
SugCompound loadedSugCompound = SugCompound.fromJson(response.body);
List<String> compoundList = loadedSugCompound.compound;
compoundList = compoundList
.where((element) => element.toLowerCase().contains(query.toLowerCase()))
.toList();
return compoundList;
} else {
throw Exception();
// }
}
Now the future returns a list of what you searched, put this in FutureBuilder and show it into screen
I am trying to convert a customContact into a json to save it in my shared Preference in flutter. but i am being bombareded by this error. i tried all suggestions but i am not able to find out the exact answer. Find below my code,
class CustomContact extends Contact {
Contact contact;
bool isChecked;
CustomContact({
this.contact,
this.isChecked = false,
});
Map<String, dynamic> toJson() => {
'contact': contact,
'isChecked': isChecked,
};
CustomContact.fromJson(Map<String, dynamic> json)
: contact = json['contact'],
isChecked = json['isChecked'];
}
Where i am trying to encode,
_saveTrustedContactsNames() async {
final prefs = await SharedPreferences.getInstance();
List<CustomContact> _saveList = [];
for (var item in contactsSelected) {
print(item.contact.displayName);
_saveList.add(item);
}
prefs.setString('cust1', json.encode(_saveList)); // i am thrown error here saying
//"JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of
//'CustomContact')"
}
Trying to save a list in shared sharedpreferences by converting to JsonString. But repeatedly getting the encodable object failed : Instance of 'CustonContact'. Help out
class CustomContact extends Contact{
Contact contact;
bool isChecked;
CustomContact({
this.contact,
this.isChecked = false,
});
Map toJson() {
return {
'contact': contact,
'isChecked': isChecked,
};
}
CustomContact.fromJson(Map<String, dynamic> json)
: contact = json['contact'],
isChecked = json['isChecked'];
}
****Trying to call it in here to save in sharedpreference****
_saveTrustedContactsNames() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
List<CustomContact> _contactsSelectedNames = [];
for (var _customContact in contactsSelected) { **contactsSelected is already populated**
setState(() {
_contactsSelectedNames.add(_customContact);
});
}
**trying to convert to JsonString**
String _trustedContactsJson = jsonEncode(_contactsSelectedNames);
print(_trustedContactsJson);
preferences.setString('_contactstrusted', _trustedContactsJson);
}
That's cause sharedPreferences can't automatically convert Contact to json. You'll need to create a toJson method in Contact and pass that method in to your CustomContact's toJson method and vice versa for the fromJson.
Map toJson() {
return {
'contact': contact.toJson(),
'isChecked': isChecked,
};
}
CustomContact.fromJson(Map<String, dynamic> json)
: contact = Contact.fromJson(json['contact']),
isChecked = json['isChecked'];
i have class that generate json list this is my class
class Tool{
String Name;
bool selection;
String englishName;
Map<String, dynamic> toJson() {
return {
'Name': persianName,
'selection': selection,
'englishName': englishName
};
}
}
List<Tool> tools=new List();
setTool(tool){
tools.add(tool);
}
toolsLength(){
return tools.length;
}
updatetool(index,goal){
tools[index]=goal;
}
getTool(index){
return tools[index];
}
getAllTools(){
return tools;
}
and this is dio library that send my list to server every thing is ok but my array is into Double quotation in other word my list is string how to pick up double quotation around of json array . if assume my json array hase
"tools": [{"name":"jack","selection" : false " ,"englishName":"jock"}]
result is :
"tools": "[{"name":"jack","selection" : false " ,"englishName":"jock"}]"
how fix it this is my class for send
FormData formData = new FormData.from({
"tools":jsonEncode(getAllTools().map((e) => e.toJson()).toList()) ,
});
response = await
dio.post("${strings.baseurl}/analyze/$username/$teacher", data:
formData);
print("----------> response is :"+response.toString());
Edit
You can paste the following code to DarPad https://dartpad.dartlang.org/
The following demo shows transform your Json String to Tool List and Convert your Tool List to JSON string again and use map.toJson
var yourresult = toolList.map((e) => e.toJson()).toList();
you can see result in picture
use FormData.from need to know what your api's correct JSON String.
Please test your web api with Postman, if you success, you will know correct format string.
In your code
FormData formData = new FormData.from({
"tools":jsonEncode(getAllTools().map((e) => e.toJson()).toList()) ,
});
if you are trying to to do
FormData formData = new FormData.from({
"tools":'[{"name":"jack","selection" : false ,"englishName":"jock"}, {"name":"jack2","selection" : false ,"englishName":"jock2"}]' ,
});
so you can get your json string first and put it in FormData
var toolsJson = toolsToJson(toolList);
FormData formData = new FormData.from({
"tools":toolsJson ,
});
full demo code, you can paste to DartPad to see string and list conversion
import 'dart:async';
import 'dart:io';
import 'dart:core';
import 'dart:convert';
class Tools {
String name;
bool selection;
String englishName;
Tools({
this.name,
this.selection,
this.englishName,
});
factory Tools.fromJson(Map<String, dynamic> json) => new Tools(
name: json["name"],
selection: json["selection"],
englishName: json["englishName"],
);
Map<String, dynamic> toJson() => {
"name": name,
"selection": selection,
"englishName": englishName,
};
}
main() {
List<Tools> toolsFromJson(String str) => new List<Tools>.from(json.decode(str).map((x) => Tools.fromJson(x)));
String toolsToJson(List<Tools> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
var toolsStr = '[{"name":"jack","selection" : false ,"englishName":"jock"}, {"name":"jack2","selection" : false ,"englishName":"jock2"}]';
var toolList = toolsFromJson(toolsStr);
var toolsJson = toolsToJson(toolList);
print("toolsJson ${toolsJson} \n");
var toolsmap = toolList[0].toJson();
print("toolsmap ${toolsmap.toString()}\n");
var yourresult = toolList.map((e) => e.toJson()).toList();
print(yourresult.toString());
}
you can paste your JSON string to https://app.quicktype.io/, you will get correct Dart class
correct JSON string of your sample. in false keyword followed by a " cause JSON string parsing error.
[
{"name":"jack",
"selection" : false ,
"englishName":"jock"
}
]
code to parse JSON string and encode to List, use toJson will convert to JSON string you need to send with dio form
// To parse this JSON data, do
//
// final tools = toolsFromJson(jsonString);
import 'dart:convert';
List<Tools> toolsFromJson(String str) => new List<Tools>.from(json.decode(str).map((x) => Tools.fromJson(x)));
String toolsToJson(List<Tools> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
class Tools {
String name;
bool selection;
String englishName;
Tools({
this.name,
this.selection,
this.englishName,
});
factory Tools.fromJson(Map<String, dynamic> json) => new Tools(
name: json["name"],
selection: json["selection"],
englishName: json["englishName"],
);
Map<String, dynamic> toJson() => {
"name": name,
"selection": selection,
"englishName": englishName,
};
}
I am trying to work with firebase database from flutter. I have made a model class which I am converting to json and from json via plugin json_serializable. Where model class works perfectly fine with hard coded json data but when I am trying to save the encoded data to firebase database it's getting saved as a string instead of key value pair in firebase database.Below is my code to convert it and save it
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
//print(json.encode(egluCard));
// var jsonString = '{"isInternal":true,"isPublished":true,"title":"HI","body":"World","caption":"Awesome","cardType":"TYPE_1","images":["images"],"expiry":123,"showAt":125,"bgColor":"#FFFFFF","platformType":"IOS","actions":[{"label":"This is label","url":"mranuran.com"}]}';
// Map<String,dynamic> cardMap = json.decode(jsonString);
// EgluCard egluCard = EgluCard.fromJson(cardMap);
// print(egluCard.actions[0].label);
var jsonString = json.encode(egluCard);
var trimmedString = jsonString.substring(0,jsonString.length);
print(trimmedString);
cardsDBRef.push().set(jsonString)
.then((_){
print('saved!!');
});
when I am printing the json.encode(eGluCard) then it's printing a valid json but when it's getting saved into firebase I am getting the following from firebase. It was supposed to save as key value pair but it was saved as a whole string.
"{\"isInternal\":true,\"isPublished\":true,\"title\":\"HI\",\"body\":\"World\",\"caption\":\"Awesome\",\"cardType\":\"TYPE_1\",\"images\":[\"images\"],\"expiry\":123,\"showAt\":125,\"bgColor\":\"#FFFFFF\",\"platformType\":\"IOS\",\"actions\":[{\"label\":\"This is label\",\"url\":\"mranuran.com\"}]}"
what can be wrong in this approach? below are my model classed and their generated serializer respectively
EgluCard.dart
import 'card_type.dart';
import 'platform_type.dart';
import 'action.dart';
import 'package:json_annotation/json_annotation.dart';
part 'eglu_card.g.dart';
#JsonSerializable()
class EgluCard {
bool isInternal;
bool isPublished;
String title;
String body;
String caption;
CardType cardType;
List<String> images;
int expiry;
int showAt;
String bgColor;
PlatformType platformType;
List<Action> actions;
EgluCard(this.isInternal,this.isPublished,this.title,this.body,this.caption,this.cardType,this.images,
this.expiry,this.showAt,this.bgColor,this.platformType,this.actions);
factory EgluCard.fromJson(Map<String, dynamic> json) => _$EgluCardFromJson(json);
Map<String, dynamic> toJson() => _$EgluCardToJson(this);
}
EgluCard Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'eglu_card.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
EgluCard _$EgluCardFromJson(Map<String, dynamic> json) {
return EgluCard(
json['isInternal'] as bool,
json['isPublished'] as bool,
json['title'] as String,
json['body'] as String,
json['caption'] as String,
_$enumDecodeNullable(_$CardTypeEnumMap, json['cardType']),
(json['images'] as List)?.map((e) => e as String)?.toList(),
json['expiry'] as int,
json['showAt'] as int,
json['bgColor'] as String,
_$enumDecodeNullable(_$PlatformTypeEnumMap, json['platformType']),
(json['actions'] as List)
?.map((e) =>
e == null ? null : Action.fromJson(e as Map<String, dynamic>))
?.toList());
}
Map<String, dynamic> _$EgluCardToJson(EgluCard instance) => <String, dynamic>{
'isInternal': instance.isInternal,
'isPublished': instance.isPublished,
'title': instance.title,
'body': instance.body,
'caption': instance.caption,
'cardType': _$CardTypeEnumMap[instance.cardType],
'images': instance.images,
'expiry': instance.expiry,
'showAt': instance.showAt,
'bgColor': instance.bgColor,
'platformType': _$PlatformTypeEnumMap[instance.platformType],
'actions': instance.actions
};
T _$enumDecode<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
throw ArgumentError('A value must be provided. Supported values: '
'${enumValues.values.join(', ')}');
}
return enumValues.entries
.singleWhere((e) => e.value == source,
orElse: () => throw ArgumentError(
'`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}'))
.key;
}
T _$enumDecodeNullable<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
return null;
}
return _$enumDecode<T>(enumValues, source);
}
const _$CardTypeEnumMap = <CardType, dynamic>{CardType.TYPE_1: 'TYPE_1'};
const _$PlatformTypeEnumMap = <PlatformType, dynamic>{
PlatformType.ANDROID: 'ANDROID',
PlatformType.IOS: 'IOS',
PlatformType.ANDROID_THING: 'ANDROID_THING',
PlatformType.ANY: 'ANY'
};
Action.dart
import 'package:json_annotation/json_annotation.dart';
part 'action.g.dart';
#JsonSerializable()
class Action {
String label;
String url;
Action(this.label,this.url);
factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json);
Map<String, dynamic> toJson() => _$ActionToJson(this);
}
Action Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'action.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Action _$ActionFromJson(Map<String, dynamic> json) {
return Action(json['label'] as String, json['url'] as String);
}
Map<String, dynamic> _$ActionToJson(Action instance) =>
<String, dynamic>{'label': instance.label, 'url': instance.url};
PlatformType and CardType are enums
Okay turns out I have to decode and encoded string before passing it to firebase.
So code to save the model class to firebase will be like this:
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
var jsonString = json.encode(egluCard);
print(json.decode(jsonString));
cardsDBRef.push().set(json.decode(jsonString))
.then((_){
print('saved!!');
});