Dart - convert Webfeed to Json - flutter

I am new to dart and flutter. I am learning and trying to make an app that reads Atomic feed from the website. I am using webfeed package to accomplish this.
Here is the code I have so far -
Future<NewsModel> fetchLatestNews() async {
final response = await client.get("https://www.example.com/blog-news-list/atom/");
if(response.statusCode == 200){
var atomFeed = new AtomFeed.parse(response.body);
Map map = new Map();
for (int i = 0; i < atomFeed.items.length; i++) {
map[i]["title"] = atomFeed.items[i].title;
map[i]["link"] = atomFeed.items[i].id;
map[i]["published"] = atomFeed.items[i].published;
map[i]["summary"] = Helpers.removeAllHtmlTags(atomFeed.items[i].summary);
}
return NewsModel.fromJson(json.decode(map.toString()));
}else {
throw Exception("Failed to load post.");
}
}
And here is my news_model.dart
class NewsModel{
List<_Result> _results = [];
NewsModel.fromJson(Map<String, dynamic> parsedJson) {
List<_Result> temp = [];
for (int i = 0; i < parsedJson.length; i++) {
_Result result = _Result(parsedJson[i]);
temp.add(result);
}
_results = temp;
}
List<_Result> get results => _results;
}
class _Result {
String _title;
String _link;
String _published;
String _summary;
List<String> _categories = [];
_Result(result) {
_title = result['title'];
_link = result['link'];
_published = result['published'];
_summary = result['summary'];
for (int i = 0; i < result['category'].length; i++) {
_categories.add(result['category'][i]);
}
}
String get published => _published;
String get title => _title;
String get link => _link;
String get summary => _summary;
List<String> get categories => _categories;
}
These code didn't work. I know I am doing it wrong, but my problem will be solved if either of the following question is answered -
how could I convert AtomFeed to Json?
Or change in model that could reflect the feed without converting it to Json.
Any help will be highly appreciated

With this you already have an object that could reflect the feed:
AtomFeed atomFeed = AtomFeed.parse(response.body);
AtomFeed

Related

Dart: CloudFirestore: Firebase -> How to pass firestore query operator as variable Query<T>.where(key, operator, value)

Firestore with Dart requires query operators to be passed as objects.
Docs: https://firebase.google.com/docs/firestore/query-data/queries
Ex Dart:
.where("key", isEqualTo: value)
Ex Go:
.where("key", "==", value).
In the case of go, passing a string "==" as the query operator is pretty straight forward.
For dart, i am trying to figure out how to store isEqualTo: as a variable, to then pass into the function.
Ok here is my code. Any help is really appreciated thank you!
Here is the DataModel
class FirestoreQueryModel extends Equatable {
//Variables
final String property;
final FirestoreOperatorEnum operator;
// This is the value where i want to store the list of operators
final dynamic value;
}
Here is the current repository
class CustomerRepository{
late Query golbalQuery
Stream <List<CustomerModel>> dynmamicCollectonStream(List<FirestoreQueryModel> queryList,) { //If query list is null, do not apply where clause
if (queryList.isEmpty) { return collectionRef().snapshots().map((doc) {var returnedList = doc.docs; var mappedList = returnedList.map((doc) => CustomerModel.fromDocument(doc)).toList();
return mappedList;
});
} else {var count = queryList.length; CollectionReference cRef = collectionRef();
for (var i = 0; i < count; i++) { golbalQuery = cRef.where(queryList[i].property, isEqualTo: queryList[i].value); }
var list = golbalQuery.snapshots().map((doc) { var returnedList = doc.docs; var mappedList = returnedList.map((doc) =\> CustomerModel.fromDocument(doc)).toList(); return mappedList; }); return list; } }}
In the for loop, where we convert the data model to a where clause I currently have hardcoded isEqualTo:
The goal is to convert
for (var i = 0; i < count; i++) { golbalQuery = cRef.where(queryList[i].property, isEqualTo: queryList[i].value); }
to
for (var i = 0; i < count; i++) { golbalQuery = cRef.where(queryList[i].property, qyeryList[i].operator, queryList[i].value); }

Dart: Sum values in list based on condition: Calculate List value based on ID?

I have list, I want to get total number of quantities available
var itemlist=[{"item_name":"32inch Tv","barnd":"samsung","qty":12},
{"item_name":"32inch Tv","barnd":"realme","qty":10},
{"item_name":"55inch Tv","barnd":"samsung","qty":10},
{"item_name":"55inch Tv","barnd":"mi","qty":36},
{"item_name":"40inch Tv","barnd":"sony","qty":20},
{"item_name":"40inch Tv","barnd":"vu","qty":12}];
in dart how to get sum of "qty" based on "item_name"?
like
32inch Tv =22
55inch Tv =46
40inch Tv =32
how to get this result???
as
List<int> qty=[22,46,32];
What you need to do is, collect all in a map as a key value pair and get the quantities at the end by adding one by one.
void main() {
final itemlist = [{"item_name":"32inch Tv","barnd":"samsung","qty":12},
{"item_name":"32inch Tv","barnd":"realme","qty":10},
{"item_name":"55inch Tv","barnd":"samsung","qty":10},
{"item_name":"55inch Tv","barnd":"mi","qty":36},
{"item_name":"40inch Tv","barnd":"sony","qty":20},
{"item_name":"40inch Tv","barnd":"vu","qty":12}];
final values = <String, int>{};
for (int i = 0; i < itemlist.length; i++) {
final item = itemlist[i];
final itemName = item['item_name'] as String;
final qty = item['qty'] as int;
int previousValue = 0;
if (values.containsKey(itemName)) {
previousValue = values[itemName]!;
}
previousValue = previousValue + qty;
values[itemName] = previousValue;
}
final result = values.values;
print('result: $result');
}
void main() {
var itemlist=[{"item_name":"32inch Tv","barnd":"samsung","qty":12},
{"item_name":"32inch Tv","barnd":"realme","qty":10},
{"item_name":"55inch Tv","barnd":"samsung","qty":10},
{"item_name":"55inch Tv","barnd":"mi","qty":36},
{"item_name":"40inch Tv","barnd":"sony","qty":20},
{"item_name":"40inch Tv","barnd":"vu","qty":12}];
var result = itemlist
.where((e) => e['item_name'] == '55inch Tv')
.map((e) => e['qty'] as int)
.reduce((x,y) => x+y);
print(result);
}
Output:
46

Flutter - Function - Return Array

I've build an List with 44 places:
List<String> departmentdes = new List(44);
after that I've called a function:
postDepartment();
The function is an api call:
postDepartment() async {
final response = await http.get('url');
final jsonresponse = json.decode(response.body);
List<Department> departments = [];
for(var d in jsonresponse) {
Department department = Department(
fid: d["fid"].toString(),
);
departments.add(department);
}
int index = departments.length -1;
for(int i = 0; i<=index; i++) {
departmentdes[i] = departments[i].fid;
}
return departmentdes;
}
After the postDepartment(); I want to print the departmentdes but it always returns null. Why?
i < index
You're already defining index to be length -1
Just a little logic error.
Change your postDepartment to this and see if it helps:
Future<void> postDepartment() async {
final response = await http.get('url');
final jsonresponse = json.decode(response.body);
List<Department> departments = [];
for(var d in jsonresponse) {
Department department = Department(
fid: d["fid"].toString(),
);
departments.add(department);
}
int index = departments.length -1;
for(int i = 0; i<=index; i++) {
departmentdes[i] = departments[i].fid;
}
return departmentdes;
}
Also check if your departments is not null.

Sort out dates for flutter check box/ Date scheduler

I have a service which returns a list of dates, which the user can opt for a future payment.
In the UI, there are three drop down boxes, one each for year, month and date.
Now when the user selects a particular year, then the months shown in the next drop down should only contain months corresponding to that particular selected year and similarly when the month is selected only the corresponding dates to that particular selected month should be shown.
The service response is something like below :
[
{
"availableDate":"03/13/2020"
},
{
"availableDate":"04/14/2020"
},
{
"availableDate":"01/15/2020"
},
{
"availableDate":"01/16/2020"
},
{
"availableDate":"02/17/2020"
},
{
"availableDate":"02/18/2020"
},
{
"availableDate":"02/22/2021"
}
]
I was able to split out the dates,months and years and when I tried to change values using onChange, didn't get the desired result. Could some one please help me with the logic or maybe give me a link to get started?
I have found out a solution.
First initialize the variables :
List _serviceData = [];
List _yearList = [];
List _monthList = [];
List _dateList = [];
List<SchedulerYear> _yearData = new List<SchedulerYear>();
List<SchedulerMonth> _monthData = new List<SchedulerMonth>();
List<SchedulerDate> _dateData = new List<SchedulerDate>();
var yearData = [];
var monthData = [];
var _loadData, _year, _month, _date;
Models used :
class SchedulerYear {
String year;
String month;
String date;
SchedulerYear({this.year,this.month,this.date});
#override
String toString() {
return '$year $month $date';
}
}
class SchedulerMonth {
String month;
String date;
SchedulerMonth({this.month,this.date});
#override
String toString() {
return '$month $date';
}
}
class SchedulerDate {
String date;
SchedulerDate({this.date});
#override
String toString() {
return '$date';
}
}
And finally the functions :
List<DropdownMenuItem<String>> getMenuItems(List options) {
List<DropdownMenuItem<String>> items = List();
for (String n in options) {
items.add(DropdownMenuItem(value: n, child: Text(n)));
}
return items;
}
_getYears() async {
_serviceData = await serviceHandler.fadfj; // the service response as a List
_yearData = [];
_yearList = [];
_yearItems = [];
for (int i = 0; i < _serviceData.length; i++) {
_loadData = _serviceData[i].toString();
_month = _loadData.split('/')[0];
_date = _loadData.split('/')[1];
_year = _loadData.split('/')[2];
_yearData.add(SchedulerYear(year: _year, month: _month, date: _date));
_yearList.add(_year);
}
_yearList = _yearList.toSet().toList();
_yearItems = getMenuItems(_yearList);
_selectedYear = _yearItems[0].value;
yearData = _yearData;
}
_getMonths(selectedYear) {
_dateItems = [];
_dateItems = getMenuItems(_initialDate);
_selectedDate = _dateItems[0].value;
_yearData = yearData;
_monthData = [];
_monthList = [];
_monthItems = [];
for (int i = 0; i < _yearData.length; i++) {
if (_yearData[i].year == selectedYear) {
_monthData.add(SchedulerMonth(month: _yearData[i].month, date: _yearData[i].date));
_monthList.add(_yearData[i].month);
}
}
monthData = _monthData;
_monthList = _monthList.toSet().toList();
_monthItems = getMenuItems(_monthList);
_selectedMonth = _monthItems[0].value;
}
_getDates(selectedMonth) {
_monthData = monthData;
_dateData = [];
_dateList = [];
_dateItems = [];
for (int i = 0; i < _monthData.length; i++) {
if (_monthData[i].month == selectedMonth) {
_dateData.add(SchedulerDate(date: _monthData[i].date));
_dateList.add(_monthData[i].date);
}
}
_dateList = _dateList.toSet().toList();
_dateItems = getMenuItems(_dateList);
_selectedDate = _dateItems[0].value;
}
_getYears() is called inside init() and the _getMonths(selectedYear) is called onChange of years dropdown button and _getDates(selectedMonth) on the months dropdown button

string contains inside of attribute of list

I wanted to display contact which has id = 'asdf-123' from List of class Contact which have attributes [id, name, phone, dob].
i can do it by doing
bool isContainId = false;
String testId = 'asdf-123';
contacts.foreach((contact) {
if (contact.id == testId) {
isContainId = true;
}
});
however, is there any better way of doing it. something like .contains. please help!.
Contains can not work with custom models in dart, you have to traverse through each object for this kind of operation.
bool isContainId = false;
String testId = 'asdf-123';
isContainId = contacts.firstWhere((contact)=> contact.id == testId, orElse: (){isContainId = false;}) != null;
UPDATE:
class CustomModel {
int id;
CustomModel({this.id});
}
void main() {
List<CustomModel> all = [];
for (var i = 0; i < 4; i++) {
all.add(CustomModel(id: i));
}
bool isContainId = false;
isContainId = all.firstWhere((contact)=> contact.id == 5, orElse: (){isContainId = false;}) != null;
print(isContainId);
}