Flutter - Function - Return Array - flutter

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.

Related

How to get length of String in flutter and display in firestore array

I need to create an array of information into firestore and I want to achieve this:
I have tried this:
Future uploadData(String name) async {
List<String> splitList = name.split('');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++){
for (int y = 1 ; y < splitList[i].length + 1; y++) {
indexList.add(splitList[i].substring(0,y).toLowerCase());
}
name = name + name[i];
indexList.add(name);
}
print(indexList);
FirebaseFirestore.instance.collection('Users').doc(_auth.currentUser!.uid).update({
'arrayUser': indexList
});
}
but it crash the application...
Hi have found a way to achieve what I needed.
Hope that can help the community:
Future nameArray(String name) async {
List<String> arrName = [];
String s = name.toLowerCase();
String e = '';
for (int i = 0; i < s.length; i++) {
e = e + s[i];
arrName.add(e);
}
FirebaseFirestore.instance.collection('Users').doc(_auth.currentUser!.uid).update({
'userArray': FieldValue.arrayUnion(arrName)
});

variable doesn't get value from for loop

Why is the Value of Response response not getting the value from the inner for loops response? Its value stays ""
Future getArticle() async {
final data1 = await fetchArticles();
Response response = Response("", 200);
for (int i = 0; i == data1.length; i++) {
response = await get(
Uri.parse('https:/url/' +
data1[i]["file"]),
);
return response; //I want it to have this responses value
}
String data2 = (response.body);
return data2;
}
The for loop you post is like this :
for (int i = 0; i == data1.length; i++) {
response = await get(
Uri.parse('https:/url/' +
data1[i]["file"]),
);
This won't trigger the i++ at all, since you are checking if i == data1.length.
Change it to i < data1.length:
for (int i = 0; i < data1.length; i++) {
response = await get(
Uri.parse('https:/url/' +
data1[i]["file"]),
);
This will make sure it fully loops through the entire length of data1.
This loop doesn't make sense. It will always return the first element and exit the loop in which case you don't need a loop. If you want a loop then do this:
data1.forEach((value) => {
response = await get(
Uri.parse('https:/url/' +
value["file"]),
);
return response.body;
});

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

Dart - convert Webfeed to Json

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

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);
}