audio_service new update removed fromjson in model class .. how can i add media item from json? My json look like this
[
{
"id": "http://581.22.00.66:8500/1?type=http",
"title": "test",
"artist": "test",
"album": "test",
"artUri": "test.png",
"genre": "8535",
"displayDescription": "23"
},
{
"id": "http://581.22.00.66:6600/2?type=http",
"title": "test2",
"artist": "test2",
"album": "test2",
"artUri": "test2.png",
"genre": "1498",
"displayDescription": "23"
},
we using dio for json.
List<MediaItem> _queue = [];
void getdata() async {
final response = await Dio().get(Constants.url+'post.php', queryParameters: {
});
for (int i = 0; i < response.data.length; i++) {
_queue.add(response.data[i]);
}
}
Error:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'MediaItem'
If there is no default method to do that, you can create a JSON(map) parser function to audio_service's Media model.
Note: parser function converts only the fields that you provide on your json data.
MediaItem jsonToMeidaItem(Map data) {
return MediaItem(
id: data['id'].toString(),
title: data['title'].toString(),
artist: data['artist'].toString(),
album: data['album'].toString(),
artUri: data['artUri'].toString(),
genre: data['genre'].toString(),
displayDescription: data['displayDescription'].toString(),
);
}
Then you could be able to convert JSON data to MediaItem.
Substituted converter-function to your code:
List<MediaItem> _queue = [];
void getdata() async {
final response = await Dio().get(Constants.url+'post.php', queryParameters: {
});
for (int i = 0; i < response.data.length; i++) {
final MediaItem mediaItem = jsonToMeidaItem(response.data[i]);
_queue.add(mediaItem);
}
}
Related
Here is the file causing the problem:
import 'package:http/http.dart' as http;
import './question_model.dart';
import 'dart:convert';
class DBconnect {
final url = Uri.parse(
'https://quizzapp-f2354-default-rtdb.firebaseio.com/questions.json');
Future<List<Question>> fetchQuestions() async {
return http.get(url).then((response) {
var data = json.decode(response.body) as Map<String, dynamic>;
List<Question> newQuestions = [];
data.forEach((key, value) {
var newQuestion = Question(
id: key,
title: value['title'],
options: Map.castFrom(value['options']),
);
newQuestions.add(newQuestion);
});
return newQuestions;
});
}
}
Here's the JSON file that I loaded into the firebase realtime database:
{
"questions": {
"first": {
"title": "Who is the best player in the world?",
"options": {
"messi": "true",
"ronaldo": "false",
"haaland": "false",
"mbappe": "false"
}
},
"second": {
"title": "2 + 2 = ?",
"options": {
"1": "false",
"2": "false",
"3": "false",
"4": "true"
}
}
}
}
I tried running the app and was expecting the questions to load in the app.
/// A problem occurred because the API was not working properly, replace your code with this and try
class DBconnect {
final url = Uri.parse('https://quizzapp-f2354-default-rtdb.firebaseio.com/questions.json');
Future<List<Question>> fetchQuestions() async {
return http.get(url).then((http.Response? response) {
if (response?.statusCode == 200 || response?.statusCode == 201) {
var data = json.decode(response!.body) as Map<String, dynamic>;
List<Question> newQuestions = [];
data.forEach((key, value) {
var newQuestion = Question(
id: key,
title: value['title'],
options: Map.castFrom(value['options']),
);
newQuestions.add(newQuestion);
});
return newQuestions;
} else {
return [];
}
});
}
}
how to accommodate an input into a list array with shared preferences?
I made a code like below
handlesave() async {
SharedPreferences ref = await SharedPreferences.getInstance();
List<String> _arr = [];
var idU = user.user.id;
final dataJ = JobStorageModel(
iduser: idU.toString(),
id: widget.job.id,
job_title: widget.job.job_title,
location: widget.job.location,
);
String json = jsonEncode(dataJ);
print('save -> $json');
ref.setString('bookmark', json);
}
so that it becomes a list array like the following
{
"ID": 1,
"iduser": "1",
"job_title": "Designer",
"location": "monggola"
},
{
"ID": 2,
"iduser": "1",
"job_title": "UX",
"location": "singapore"
}
So i'm trying to create a list with objects of type 'MessageListItem'. I'm trying to push data returned from my API into the list. The variable I want it pushed into is 'messages'. I am getting an error in the 'getMessages()' function.
The error I am getting is: A value of type 'MessageListItem' can't be assigned to a variable of type 'List'.
The API call & code is:
List<MessageListItem> messages;
getMessages() async {
List<MessageListItem> res = MessageListItem.fromJson(await getMessageList());
// I'm getting the error on the line above.
print(res);
}
Future<dynamic> getMessageList() async {
final response = await http.get(baseUrl + 'message/jxchumber');
print(response.statusCode);
if (response.statusCode == 200) {
var res = json.decode(response.body);
return res;
} else {
throw Exception('Failed to get data');
}
}
MessageListItem Class
class MessageListItem {
int id;
int senderId;
int recipientId;
String senderUsername;
String recipientUsername;
int itemId;
String messageContentString;
bool read;
dynamic dateTimeSent;
MessageListItem(
{this.id,
this.senderId,
this.recipientId,
this.senderUsername,
this.recipientUsername,
this.itemId,
this.messageContentString,
this.read,
this.dateTimeSent});
factory MessageListItem.fromJson(Map<String, dynamic> json) {
return MessageListItem(
id: json['id'],
senderId: json['senderId'],
recipientId: json['recipientId'],
senderUsername: json['senderUsername'],
recipientUsername: json['recipientUsername'],
itemId: json['itemId'],
messageContentString: json['messageContentString'],
read: json['read'],
dateTimeSent: json['dateTimeSent'],
);
}
}
The data being returned from the API is:
[
{
"id": 4,
"senderId": 1,
"recipientId": 3,
"senderUsername": "jxchumber",
"recipientUsername": "pavster31",
"itemId": 0,
"messageContentString": "hello1",
"read": false,
"dateTimeSent": "2020-12-14T22:23:55.1473414"
},
{
"id": 3,
"senderId": 1,
"recipientId": 9,
"senderUsername": "jxchumber",
"recipientUsername": "larsen",
"itemId": 0,
"messageContentString": "hello1",
"read": false,
"dateTimeSent": "2020-12-14T16:04:50.8232055"
}
]
I'm trying to push it into the variable 'messages'
Try this
getMessages() async {
var list = await getMessageList();
List<MessageListItem> res = list.map((i)=>MessageListItem.fromJson(i)).toList();
}
I am getting this response from the API:
[
{
"id": 1,
"company_id": 2,
"surname": "Surname",
"name": "Name",
"employee_position_id": 1,
"phone_number": "+xxx xxx xxx xxx",
"email": "mail#mail.mail",
"user_id": 1,
"contact_level": null,
"created_at": "2020-10-03T16:50:59.000000Z",
"updated_at": "2020-10-03T17:05:54.000000Z",
"deleted_at": null,
"full_name": "Surname Name",
"position_name": "IT",
"company_name": "Company One"
}
]
According to every tutorial I found, this code should work:
void _getContacts() async {
var res = await Network().getData('/contacts');
final Map<String, dynamic> body = json.decode(res.body);
// print(body.runtimeType);
}
However, it gives me this error:
E/flutter (23716): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
When I print the body.runtimeType it says List<dynamic>
I double checked, i tripple checked everything, json seems to be in a correct format, all the code seems to be written correctly.
How is it possible it gives me List instead of a Map? and how do I force the json.decode to give me a Map instead of a List?
There is List you have to iterate it.
if there is only one object of your list then you can use it like this
void _getContacts() async {
var res = await Network().getData('/contacts');
var response= json.decode(res.body);
final Map<String, dynamic> body = response[0];
// print(body.runtimeType);
}
if there is more than one object on your list then you can use it like this
void _getContacts() async {
var res = await Network().getData('/contacts');
var response= json.decode(res.body);
final Map<String, dynamic> body = response.map((e)=>e);
// print(body.runtimeType);
}
I have set of data, with some details,when i try to display the the one value returns null,other 2 data is fine,but if i try to show other data it's shows null,if i try to add that to setState,everything become null,There is no problem when i get the "Description","imagepath" i can show it, but the data from the replys object doesn't show
JSON
{
"doc": {
"image": {
"Description": "tested",
"replay": " ",
"Image_Rating": 0,
"replay_status": 0,
"Report_Date": "1591228800",
"Status": 1,
"_id": "5ed88ae73025a4445568ece3",
"image_path": "http://xxx.xxx.xxx.xxx:xxx/area_images/1670281356001.jpg",
"Created_User_Id": "5ed22c2507a33e2c1cf3a3a5",
"Branch_Id": "5ed22bf807a33e2c1cf3a3a4",
"image_temp_path": "http://xxx.xxx.xxx.xxx:xxx/area_images_temp/1670281356001.jpg",
"Order_Id": 32425,
"reg_date": "1591249638163",
"Area_Id": "5dc11c4046c214298f85e2e0",
"Section_Id": "5dc1097546c214298f85e2ae",
"Report_Time_Type": 1,
"mapperId": "5ed22c4207a33e2c1cf3a3a6",
"Created_At": "Thursday, June 4th, 2020, 11:17:18 AM",
"__v": 0
},
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
}
}
Code
Future<String> getImageView(String imageid) async {
Future token = SharedPrefrence().getToken();
token.then((data) async {
var token = data;
var response = await http.post(Urls.Image_Details,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
},
body: json.encode({
"imageId": imageid,
}));
if (response.statusCode == 200) {
try {
var resp = response.body;
Map<String, dynamic> value = json.decode(resp);
var name = value['doc']['image'];
Description = name["Description"].toString();
image_path = name["image_path"].toString();
replay = name["replays"]["replay"].toString();
setState(() {
Description = name["Description"].toString();
image_path = name["image_path"].toString();
// replay = name["replays"]["replay"].toString();
});
} catch (e) {
e.toString();
}
}
});
}
"replays" is an array. Try this: name["replays"][0]["replay"].toString()
By adding [0] it will get your first object from that array.
EDIT:
After looking at your json some more I see that name is the wrong object.
"replays" is a member of "doc" not of "image".
I think this should work:
replay = value['doc']["replays"][0]["replay"].toString();
The problem is
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
This is a List of Maps. So as we access the first element in the list you should use
replay= value['doc']["replays"][0]["replay"].toString();
that is the zeroth element of the list.