How to convert String into List of dynamic in flutter - flutter

I am working on a flutter project with firebase.
When I tried to fetch data ({id: 2021-10-13 04:48:15.582, title: Red Shirt, quantity: 1, price: 29.99}, {id: 2021-10-13 04:48:19.438, title: Mobile Phone, quantity: 1, price: 215})
So, I want to convert each map to a list of dynamic because I got this error
Error: Expected a value of type 'List< dynamic>', but got one of type 'String'
here is my code to fetch data
Future<void> fetchandSetOrders() async {
const url = "https://test-app.firebaseio.com/orders.json";
final response = await http.get(Uri.parse(url));
final List<OrderItem> loadedOrders = [];
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
extractedData.forEach((orderId, orderData) {
print(orderData['products']);
print(orderData['products'].runtimeType);
loadedOrders.add(
OrderItem(
id: orderId,
amount: orderData['amount'],
dateTime: DateTime.parse(orderData['dateTime']),
products: (orderData['products'] as List<dynamic>)
.map(
(item) => CartItem(
id: item['id'],
price: item['price'],
quantity: item['quantity'],
title: item['title'],
),
)
.toList(),
),
);
});
_orders = loadedOrders.reversed.toList();
notifyListeners();}

Related

I got an error when trying to get data from the API error type 'null' is not a subtype of type 'string'

hello permission to ask I'm trying to get the API to then display and the response is 200 ok. but when I try to display it on the screen the following error occurs
this is a function to get data from API
Future<Datum> getPaketKuliah() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return Datum.fromJson(jsonDecode(response.body));
} else {
throw Exception();
}
}
and I want to display it on the page using FutureBuilder
Container(
child: FutureBuilder<Datum>(
future: AuthProvider().getPaketKuliah(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.kelas);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
and lastly this is the model class I want to take to display on the
page
// To parse this JSON data, do
//
// final getPaket = getPaketFromJson(jsonString);
import 'dart:convert';
GetPaket getPaketFromJson(String str) => GetPaket.fromJson(json.decode(str));
String getPaketToJson(GetPaket data) => json.encode(data.toJson());
class GetPaket {
GetPaket({
required this.status,
required this.code,
required this.data,
});
String status;
String code;
Map<String, Datum> data;
factory GetPaket.fromJson(Map<String, dynamic> json) => GetPaket(
status: json["status"],
code: json["code"],
data: Map.from(json["data"])
.map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"status": status,
"code": code,
"data": Map.from(data)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
};
}
class Datum {
Datum({
this.id,
this.idDosen,
this.idMk,
required this.nidn,
this.dosen,
this.idKelasKuliah,
this.kelasKuliah,
this.prodi,
this.kelas,
this.semester,
this.kelompokKelas,
required this.kode,
this.sks,
this.jumlahKelas,
this.matakuliah,
this.smt,
this.bobotSks,
this.rencanaPertemuan,
this.jenisEvaluasi,
required this.createdAt,
required this.updatedAt,
this.createdBy,
this.updatedBy,
});
String? id;
String? idDosen;
String? idMk;
dynamic nidn;
String? dosen;
String? idKelasKuliah;
String? kelasKuliah;
String? prodi;
String? kelas;
String? semester;
String? kelompokKelas;
dynamic kode;
int? sks;
int? jumlahKelas;
String? matakuliah;
String? smt;
int? bobotSks;
int? rencanaPertemuan;
String? jenisEvaluasi;
DateTime createdAt;
DateTime updatedAt;
String? createdBy;
String? updatedBy;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
idDosen: json["id_dosen"],
idMk: json["id_mk"],
nidn: json["nidn"],
dosen: json["dosen"],
idKelasKuliah: json["id_kelas_kuliah"],
kelasKuliah: json["kelas_kuliah"],
prodi: json["prodi"],
kelas: json["kelas"],
semester: json["semester"],
kelompokKelas: json["kelompok_kelas"],
kode: json["kode"],
sks: json["sks"],
jumlahKelas: json["jumlah_kelas"],
matakuliah: json["matakuliah"],
smt: json["smt"],
bobotSks: json["bobot_sks"],
rencanaPertemuan: json["rencana_pertemuan"],
jenisEvaluasi: json["jenis_evaluasi"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
createdBy: json["created_by"],
updatedBy: json["updated_by"],
);
Map<String, dynamic> toJson() => {
"id": id,
"id_dosen": idDosen,
"id_mk": idMk,
"nidn": nidn,
"dosen": dosen,
"id_kelas_kuliah": idKelasKuliah,
"kelas_kuliah": kelasKuliah,
"prodi": prodi,
"kelas": kelas,
"semester": semester,
"kelompok_kelas": kelompokKelas,
"kode": kode,
"sks": sks,
"jumlah_kelas": jumlahKelas,
"matakuliah": matakuliah,
"smt": smt,
"bobot_sks": bobotSks,
"rencana_pertemuan": rencanaPertemuan,
"jenis_evaluasi": jenisEvaluasi,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"created_by": createdBy,
"updated_by": updatedBy,
};
}
and this is the json response
I highly recommend using library like json_serilizable to generate factory fromJson
factory Paket.romJson(Map<String, dynamic> json) => Paket(
status: json['status'] as String,
code: json['code'] as String,
data: (json['data'] as Map<String, dynamic>).map(
(k, e) => MapEntry(k, Datum.fromJson(e as Map<String, dynamic>)),
),
);
As provided api response corresponds to GetPaket class not Datum class you need to change getPaketKuliah method to
Future<Datum> getPaketKuliah() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
// --return Datum.fromJson(jsonDecode(response.body));
final paket = GetPaket.fromJson(jsonDecode(response.body));
// -- return Datum.fromJson(paket.data.entries.first.value);
return paket.data.entries.first.value;
} else {
throw Exception();
}
}

Firestore How to update an item in the array in firestore flutter

This is my firestore database structure.
I want to change is_done to true of a todo item to the todo array in the collection.
So far I am able to append an item to the todo
void addNewTodo() async {
var db = FirebaseFirestore.instance;
final querySnapshot = await db
.collection("users")
.where("email", isEqualTo: "ocsdeveloperdevice#gmail.com")
.get();
for (QueryDocumentSnapshot doc in querySnapshot.docs) {
doc.reference.update(
{
"title": FieldValue.arrayUnion(
[Todo(isDone: false, description: "Need to Join Gym August Month", title: "Gym").toJson()])
},
);
}
}
class Todo {
String? title;
String? description;
bool? isDone;
Todo({this.title, this.description, this.isDone});
factory Todo.fromJson(Map<String, dynamic> map) {
return Todo(
isDone: map['is_done'] ?? false,
description: map['description'] ?? '',
title: map['title'] ?? '');
}
Map<String, dynamic> toJson() {
return {
'title': title ?? '',
'description': description ?? '',
'is_done': isDone ?? false
};
}
}
class MyUser {
String? name;
String? email;
List<Todo>? todo;
MyUser({this.name, this.email, this.todo});
factory MyUser.fromJson(Map<String, dynamic> map) {
return MyUser(
name: map['name'] ?? '',
email: map['email'] ?? '',
todo: map['todo'] != null
? (map['todo'] as List<dynamic>)
.map((e) => Todo.fromJson(e))
.toList()
: []);
}
Map<String, dynamic> toJson() {
return {
'title': name ?? '',
'email': email ?? '',
'todo': todo?.map((e) => e.toJson()).toList()
};
}
}
How to update is_done to true of a specific todo item ?

FormatException: Unexpected character (at character 3) I/flutter (32137) error Flutter

I want to return API data when I do jsonDecode, but I am getting this error:
FormatException: Unexpected character (at character 3)
I/flutter (32137): [{Id: 0, SourceId: 0, ServiceId: 11, CategoryId: 5, Category: Valuation, De...
My response.data return a valid json but when I want to decode, I get that error, can anyone please help.
My code is below:
Future<Autogenerated?>? signInData() async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Charset": 'utf-8',
"Authorization": "Bearer $token",
},
));
print("data is here");
print(response.data.toString());
print(response.statusCode);
if (response.statusCode == 200) {
print("decoded");
print(Autogenerated.fromJson(jsonDecode(response.data.toString())));
return Autogenerated.fromJson(jsonDecode(response.data.toString()));
} else if (response.statusCode == 500) {
// call your refresh token api here and save it in shared preference
print(response.statusCode);
await getToken();
signInData();
} else {
throw Exception('Failed to load data');
}
} catch (e) {
print(e);
}
// return null;
}
My Autogenerated model
class Autogenerated {
int? id;
int? sourceId;
int? serviceId;
int? categoryId;
String? category;
String? description;
int? serviceResponsePropertyId;
int? mappingId;
bool? isVisible;
int? packageRequestId;
int? sortOrder;
Value? value;
Autogenerated(
{this.id,
this.sourceId,
this.serviceId,
this.categoryId,
this.category,
this.description,
this.serviceResponsePropertyId,
this.mappingId,
this.isVisible,
this.packageRequestId,
this.sortOrder,
this.value});
Autogenerated.fromJson(Map<String, dynamic> json) {
id = json['Id'];
sourceId = json['SourceId'];
serviceId = json['ServiceId'];
categoryId = json['CategoryId'];
category = json['Category'];
description = json['Description'];
serviceResponsePropertyId = json['ServiceResponsePropertyId'];
mappingId = json['MappingId'];
isVisible = json['IsVisible'];
packageRequestId = json['PackageRequestId'];
sortOrder = json['SortOrder'];
value = json['Value'] != null ? new Value.fromJson(json['Value']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Id'] = this.id;
data['SourceId'] = this.sourceId;
data['ServiceId'] = this.serviceId;
data['CategoryId'] = this.categoryId;
data['Category'] = this.category;
data['Description'] = this.description;
data['ServiceResponsePropertyId'] = this.serviceResponsePropertyId;
data['MappingId'] = this.mappingId;
data['IsVisible'] = this.isVisible;
data['PackageRequestId'] = this.packageRequestId;
data['SortOrder'] = this.sortOrder;
if (this.value != null) {
data['Value'] = this.value!.toJson();
}
return data;
}
}
class Value {
String? make;
String? type;
String? model;
int? year;
String? body;
String? driveType;
String? fueType;
Value(
{this.make,
this.type,
this.model,
this.year,
this.body,
this.driveType,
this.fueType});
Value.fromJson(Map<String, dynamic> json) {
make = json['make'];
type = json['type'];
model = json['model'];
year = json['year'];
body = json['body'];
driveType = json['drive_type'];
fueType = json['fue_type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['make'] = this.make;
data['type'] = this.type;
data['model'] = this.model;
data['year'] = this.year;
data['body'] = this.body;
data['drive_type'] = this.driveType;
data['fue_type'] = this.fueType;
return data;
}
}
My response.data response in console:
[{Id: 0, SourceId: 0, ServiceId: 11, CategoryId: 5, Category: Valuation, Description: AdjustedValues, Value: [],
ServiceResponsePropertyId: 474, MappingId: 0, IsVisible: true, PackageRequestId: 13853137, SortOrder: 1}, {Id: 0, SourceId: 0, ServiceId: 11, CategoryId: 1, Category: General, Description: ServiceStatus, Value: {StatusCode: 1, StatusDescription: Ok, StatusDetail:
, RestServiceStatus: null, ServiceResource: null}, ServiceResponsePropertyId: 475, MappingId: 0, IsVisible: false, PackageRequestId: 13853137, SortOrder: 1}, {Id: 0, SourceId: 0, ServiceId: 6, CategoryId: 1, Category: General, Description: CarId, Value: 120354, ServiceResponsePropertyId: 100, MappingId: 0, IsVisible: false, PackageRequestId: 13853137, SortOrder: 1}, {Id: 0, SourceId: 0, ServiceId: 6, CategoryId: 1, Category: General, Description: Year, Value: 2017, ServiceResponsePropertyId: 103, MappingId: 0, IsVisible: true, PackageRequestId: 13853137, SortOrder: 6}, {Id: 0, SourceId: 0, ServiceId: 6, CategoryId: 1, Category: General, D
I don't get why it is printing this, because on postman, it is returning a valid json.
The error appears on this line
return Autogenerated.fromJson(jsonDecode(response.data.toString()));
Instead of:
return Autogenerated.fromJson(jsonDecode(response.data.toString()));
Try:
return List<Autogenerated>.from(response.data.map((i) => Autogenerated.fromJson(i)));
If this does not work, you should check json serializable package in order to automate the process of creating the fromJson and toJson methods
Hi guys I managed to find a solution to my problem, first I got the error I posted in the question, because my JSON response was invalid so I had to encode my response first, so I did:
print(json.encode(response.data)); to get a valid json response.
The second error was type 'List' is not a subtype of type 'Map<String, dynamic>' and I used this link Flutter 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' for assistance, thank you to everyone who helped in the comment.

Flutter : " type 'Teams' is not a subtype of type 'int' in type cast " error comes from request

I have problem with send request in Flutter ,I have this model :
import 'dart:convert';
List<Teams> teamsFromJson(String str) =>
List<Teams>.from(json.decode(str).map((x) => Teams.fromJson(x)));
String teamsToJson(List<Teams> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Teams {
Teams({
this.club,
this.price,
this.surename,
this.id,
this.league,
});
final club;
final price;
final surename;
final id;
final league;
factory Teams.fromJson(Map<String, dynamic> json) => Teams(
club: json["club"],
price: json["price"],
surename: json["surename"],
id: json["id"],
league: json["league"],
);
Map<String, dynamic> toJson() => {
"club": club,
"price": price,
"surename": surename,
"id": id,
"league": league,
};
}
I add initial values and update them in provider :
List<Teams> get teams => _teams;
List<Teams> _teams = [
Teams(club: "", price: 0, surename: "", id: "", league: ""),
Teams(club: "", price: 0, surename: "", id: "", league: ""),]
addToTeam(data, index) {
teams[index]=Team(club: data.club,
price: data.price,
surename: data.surname,
id: data.id,
league: data.leagueName);
}
and it works fine ,now I want to send the list teams as a request ,I add button and create method like this :
onPressed: () {
ApiService().saveTeam(teamsProvider.teams);
}
on ApiService I have this request :
class ApiService {
var url = 'http://10.0.2.2:8000/api/v1';
Future saveTeam(data) async {
var newurl = Uri.parse(url + '/send_test');
try {
var response = await http.post(newurl, body: data);
var result = jsonDecode(response.body);
print(result);
} catch (e) {
print('error : $e');
}
}
}
the api request is just return the request in laravel :
public function send_test(Request $request)
{
return $request;
}
as a result I get this error mesage : type 'Teams' is not a subtype of type 'int' in type cast
How can I solve this?
I solved it by myself ,I converted the Team list to Sting and decoded it with json:
class ApiService {
var url = 'http://10.0.2.2:8000/api/v1';
Future saveTeam(List<Teams> data) async {
var list = [];
data.map((e) {
list.add({
"club": e.club,
"price": e.price,
"surename": e.surename,
"id": e.id,
"league": e.league
});
}).toList();
try {
var newurl = Uri.parse(url + '/send_test');
var response = await http.post(newurl, body: jsonEncode(list));
var result = jsonDecode(response.body);
print(result);
} catch (e) {
print('error : $e');
}
}
}
then in api in laaravel/lumen received the json and decoded it again :
public function send_test(Request $request)
{
$result = json_decode($request->getContent(), true);
return $result;
}

How to Generate map from class

I have an events class thats like this
MyEvents(id: 5a9c120ab3473,
title: "Event 1",
description: "",
image: "",
isDone false,
classDate: 2019-08-23 00:00:00.000)
I'm getting a list from a database but i cant figure out how to turn it into this format for a calendar package (there could be multiple events on each day)
Map<DateTime, List<Map<String, Object>>> _events2 = {
DateTime(2019, 8, 24): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2019, 8, 24): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2019, 8, 23): [
{'name': 'Event A', 'isDone': true},
],
};
I've tried this, not sure if I'm on the right track or totally lost
events.map((c) {
print(c.title);
item = {
c.classDate: [
{'name': c.title, 'isDone': true},
]
};
mainList.add(item);
}).toList();
You can add a method in your class like this:
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
data['description'] = this.description;
data['image'] = this.image;
data['isDone'] = this.isDone;
data['classDate'] = this.classDate;
return data;
}
Found this solution
turned out to be exactly what i needed
events.map((c) {
print(c.title);
item = {'name': c.title, 'isDone': true, "class_date": c.classDate};
mainList.add(item);
}).toList();
print("collection");
var c = Collection(mainList.toList());
var result = c
.groupBy$1((e) => e["class_date"],
(e) => {"name": e["name"], "isDone": e["isDone"]})
.toDictionary$1((e) => e.key, (e) => e.toList());