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();
}
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 [];
}
});
}
}
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;
}
I'm trying out http requests from flutter to my backend.
My JSON is like this:
"_hits": {
"Do8HpM3w0mh99SF": {
"docid": "Do8HpM3w0mh99SF"
},
"HNLvkccTCIlmrcQ": {
"docid": "HNLvkccTCIlmrcQ"
},
"QNSInDU2BJMF5SD": {
"docid": "QNSInDU2BJMF5SD"
},
"UVDfRueZXIVCssk": {
"docid": "UVDfRueZXIVCssk"
},
"Y9bNKklTr2Sg6Ai": {
"docid": "Y9bNKklTr2Sg6Ai"
},
"kJgwwMbgF6PBwmMJSiKC": {
"docid": "kJgwwMbgF6PBwmMJSiKC"
},
"py5MbGK11SsbXQ1": {
"docid": "py5MbGK11SsbXQ1"
}
}
My code to request:
Future<SearchResults> fetchJson() async {
final response =
await http.get('MyWebsite.com');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
// print(response.body);
return SearchResults.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load request');
}
}
The Search Results Class:
class SearchResults {
final String hits;
SearchResults({this.hits});
factory SearchResults.fromJson(Map<String, dynamic> json) {
return SearchResults(
hits: json['_hits'],
);
}
}
What I'm trying to achieve:
Print the value of docid under the array of _hits
Coming From iOS Swift, this is very new to me, any input is greatly appreciated.
Your SearchResuts object is wrong as _hits is not a String but a Map<String, dynamic> to do it simple :
class SearchResults {
Map<String, dynamic> hHits;
SearchResults({this.hHits});
SearchResults.fromJson(Map<String, dynamic> json) {
hHits = json['_hits'];
}
}
From here, you can iterate on your docids by getting a list of _hits elements like this :
print(searchResults.hHits.values.toList());
will print
[{docid: Do8HpM3w0mh99SF}, {docid: HNLvkccTCIlmrcQ}, {docid: QNSInDU2BJMF5SD}, {docid: UVDfRueZXIVCssk}, {docid: Y9bNKklTr2Sg6Ai}, {docid: kJgwwMbgF6PBwmMJSiKC}, {docid: py5MbGK11SsbXQ1}]
I want to develop a flutter app and I am finding it difficult to parse this JSON I have seen posts regarding this but I am finding it difficult to parse this. Help a beginner out! Here is the JSON link " https://api.covid19india.org/state_district_wise.json "
I am simply using:
Future getJsonDistrictData() async {
var response = await http.get(Uri.encodeFull(url1));
var converttojson1 = json.decode(response.body);
setState(() {
myData= converttojson1;
});
}
Text("${myData['Kerala']['districtData']['Thrissur']['confirmed']}")
But this would mean I have to write the same line for every district confirmed cases.
How should I proceed?
I have made the following example of an implementation you can use the parse the data from the URL in your question.
It can be simplified if you don't need the lastUpdatedTime and delta_confirmed since it looks like this is always the empty String and zero in the API.
import 'dart:convert';
class State {
final Map<String, DistrictData> districts = {};
State.fromJson(dynamic json) {
for (final district in json['districtData'].keys) {
districts[district as String] =
DistrictData.fromJson(json['districtData'][district]);
}
}
#override
String toString() => districts.toString();
}
class DistrictData {
final int confirmed;
final DateTime lastUpdatedTime;
final int delta_confirmed;
DistrictData(this.confirmed, this.lastUpdatedTime, this.delta_confirmed);
factory DistrictData.fromJson(dynamic json) => DistrictData(
json['confirmed'] as int,
(json['lastupdatedtime'].isEmpty as bool)
? null
: (DateTime.parse(json['lastupdatedtime'] as String)),
json['delta']['confirmed'] as int);
#override
String toString() =>
'{ confirmed: $confirmed, lastUpdatedTime: $lastUpdatedTime, delta_confirmed: $delta_confirmed }';
}
void main() {
final states = json.decode(input).map(
(String key, dynamic value) => MapEntry(key, State.fromJson(value)))
as Map<String, State>;
states.forEach((key, value) => print('$key : $value'));
/*
Kerala : {Thrissur: { confirmed: 13, lastUpdatedTime: null, delta_confirmed: 0 }, Alappuzha: { confirmed: 5, lastUpdatedTime: null, delta_confirmed: 0 }}
Delhi : {East Delhi: { confirmed: 1, lastUpdatedTime: null, delta_confirmed: 0 }}
*/
}
const input = '''
{
"Kerala": {
"districtData": {
"Thrissur": {
"confirmed": 13,
"lastupdatedtime": "",
"delta": {
"confirmed": 0
}
},
"Alappuzha": {
"confirmed": 5,
"lastupdatedtime": "",
"delta": {
"confirmed": 0
}
}
}
},
"Delhi": {
"districtData": {
"East Delhi": {
"confirmed": 1,
"lastupdatedtime": "",
"delta": {
"confirmed": 0
}
}
}
}
}
''';
Copy your JSON in this link(https://javiercbk.github.io/json_to_dart/) and get model Class.
Example:
For example your Model Class Name is CovidModel. As you get response from network call, pass data to you model class and get object like this:
CovidModel _covidModel = CovidModel.fromJson(response.data);
now you can use _covidModel to get inner objects and show result in app page.
How to handle the difference between the results of a successful and failed fire response?
RESPONSE SUCCESS:
{
"header":{
"status":true,
"respcode":"00",
"message":"Successfully."
},
"data":{
"userid":"3485345",
"password":"3423424",
"bit18":"0000",
}
}
RESPONSE FAILED:
{
"header":{
"status":false,
"respcode":"01",
"message":"Userid Tidak Terdaftar"
},
"data":""
}
assuming you'll always have headers in your responses, you can do something like this:
Map<String, dynamic> res1 = {
"header": {"status": true, "respcode": "00", "message": "Successfully."},
"data": {
"userid": "3485345",
"password": "3423424",
"bit18": "0000",
}
};
Map<String, dynamic> res2 = {
"header": {
"status": false,
"respcode": "01",
"message": "Userid Tidak Terdaftar"
},
"data": ""
};
// bla = res2 for failed case
final bla = res1;
if (bla['header']['status']) {
print(res1['data']['userid']);
// do your success code here
} else {
// do your fail code here
print('fail');
}
I don't know why in the failed case, data is string (and not object). In theory, the failed case should have an empty object instead of a string. Any way, assuming you don't have control over the server's response, you might want to do something like below :
(The first two lines I wrote just to make sure the parsing works.)
Map<String, dynamic> mData = {
"header":{
"status":true,
"respcode":"00",
"message":"Successfully."
},
"data":{
"userid":"3485345",
"password":"3423424",
"bit18":"0000",
}
};
String jData = json.encode(mData);
Map<String, dynamic> decodedBody = json.decode(jData);
print(decodedBody["header"]["respcode"]); // prints 00
if (decodedBody['header']['status'])
{
User user = User.fromJson(decodedBody['data']);
print(user.userId); // This prints 3485345
}
else {
// login failed
}
And the User model is defined as below :
class User {
final String userId;
final String password;
final String bit18;
User({#required this.userId, #required this.password, this.bit18});
User.fromJson(Map json)
: this.userId = json['userid'],
this.password = json['password'],
this.bit18 = json['bit18'];
}