Good morning. I am building simple workout app in Flutter. I want to generate list of custom class Excersise:
class Excersise{
int id;
String name;
int duration;
int type;
Excersise({
required this.id,
required this.duration,
required this.name,
required this.type,
});
I want to pass parameter rounds, wtime(workout time) and ctime(cooldown time) from parent widget and then my app should create list of excersises. It should be pairs of workout and cool down time like this: wo 30sec, cd 15sec, wo 30sec, cd 15sec and so one (based on rounds value). I tried to generate this list via GET but after building this widget i get Stack overflow error. Maybe there is some error in code, maybe this is completely wrong method. Here is a code and thank for your advices.
class QuickWorkoutList extends StatelessWidget {
final int rounds;
final int wtime;
final int ctime;
QuickWorkoutList({
required this.rounds,
required this.wtime,
required this.ctime,
});
List<Excersise> get _qList {
var newEx = Excersise(id: 0, duration: 0, name: '', type: 0);
for (var i = 0; i < rounds * 2; i++) {
if (i.isEven) {
newEx.id = i;
newEx.name = 'Workout';
newEx.type = 0;
newEx.duration = wtime;
} else {
newEx.id = i;
newEx.name = 'Cooldown';
newEx.type = 1;
newEx.duration = ctime;
}
_qList.add(newEx);
}
throw 'No data';
}
Your getter method _qList is wrong implemented. You should create an empty List<Excersise> and add the Workout and Cooldown there. Currently you are recursively calling your _qList which has no anchor to stop. Consequently you have an endless loop. Btw I think you mean Exercise instead of Excersise.
List<Exercise> get _qList {
// All exercises stored
final List<Exercise> exercises = [];
// Exercise properties
int duration;
String name;
int type;
for (int i = 0; i < rounds * 2; i++) {
// Get exercise properties depending on id
if (i.isEven) {
name = 'Workout';
type = 0;
duration = wtime;
} else {
name = 'Cooldown';
type = 1;
duration = ctime;
}
// Add new exercise to list
exercises.add(
Excersise(
id: i,
duration: duration,
name: name,
type: type,
),
);
}
return exercises;
}
You shouldn't call add on your _qList getter, and that creates stack overflow I guess. You should use new List and return it from your _qList getter like this:
List<Excersise> get _qList {
var newEx = Excersise(id: 0, duration: 0, name: '', type: 0);
List<Excersise> exercises = [];
for (var i = 0; i < rounds * 2; i++) {
if (i.isEven) {
newEx.id = i;
newEx.name = 'Workout';
newEx.type = 0;
newEx.duration = wtime;
} else {
newEx.id = i;
newEx.name = 'Cooldown';
newEx.type = 1;
newEx.duration = ctime;
}
exercises.add(newEx);
}
return exercises;
}
Related
I have comments variable which is dictionary type and holds the second parameter as a list
Unfortunately, despite I get the data (inputDataSnapshot) I can not get it added to the dictionary. The dictionary with the relevant key always return null
Can someone please help why this happens?
Map<String?, List<Commentp?>?>? comments;
int _pageIndex = 0;
int _limit = 3;
String get pageIndex {
return _pageIndex.toString();
}
String get limit {
return _limit.toString();
}
List<Commentp?>? commentsP({required String postuuid}) {
return comments?[postuuid] ?? [];
}
void add({
required String postuuid,
required List inputDataSnapshot,
}) {
for (int i = 0; i < inputDataSnapshot.length; i++) {
comments?[postuuid]!.add(Commentp.fromJson(inputDataSnapshot[i]));
print(comments?[postuuid]);
}
}
}```
The mistake I made was uninitialized comments variable.
I added below code to my add method and it is fine now
if (comments[postuuid] == null) {
comments[postuuid] = [];
}
i create those loops and thats work inside loops but how i can use those loop in a container ?
i want getting category in a container with nombers of categorys and the values for each category
the same thing for items
final url = "https://www.comptoir-hardware.com/home.xml";
Future<void> rssz() async {
//lire un fichier XML
final response = await get(Uri.parse(url));
setState(() {
String body = utf8.decode(response.bodyBytes);//ligne pour decodage en arabe
var channel = RssFeed.parse(body);
feed = channel;
titreprincipal = feed.title.toString();
linkprincipal = feed.link.toString();
descriptionprincipal = feed.description.toString();
authorprincipal = feed.author.toString();
for (int j = 0; j < feed.categories!.length; j++) {
final docs = feed.categories![i];
print(docs.value);**//the value not work :/ but the look j works if i do print(j); i can see the number of category, so how i can get the value too ?**
}
for (int i = 0; i < feed.items!.length; i++) {
final item = feed.items![i];
print(item.link);
}
});
I am getting back information from a websocket that might contain one or more items on each response.
I want to convert these responses to a list of custom objects.
The issue I have is where I want to use the first index (key) and second index (value) of the returned data and use them to pass into the custom object initialization to instantiate them and add them to the list.
I also want to add to the list, but if the 'name' field in an object already exists then just update that objects amount value instead of adding another copy. I will just do this with a loop, unless there is a shorter way.
Below you can see some of the attempts I have tried.
EDIT:
var listAmounts = valueMap.values.toList();
var listNames = valueMap.keys.toList();
print(listAmounts[0]);
print(listNames[0]);
for (int i = 0; i < listAmounts.length; i++) {
Person newPerson =
new Person(name: listNames[i], amount: double.parse(listAmounts[i]));
coins.add(newPerson);
print('=========');
print(newPerson.name);
print(newPerson.amount.toString());
print('=========');
}
I am not sure this is a good way as would there be a possibility that the keys/values will not be in order? From testing they are but I am not 100% sure?
Here are two examples of the message received from the websocket:
example 1
{jacob: 123.456789, steven: 47.3476543}
example 2
{henry: 54.3768574}
I have a custom class:
class Person {
double amount;
String name;
Person({
this.name = '',
this.amount = 0.0,
});
}
Here is the main code:
IOWebSocketChannel channel;
List<Person> people = [];
void openChannel() async {
channel = IOWebSocketChannel.connect(
"wss://ws.example.com/example?example=exp1,exp2,exp3");
channel.stream.listen((message) {
//print(message);
Map valueMap = json.decode(message);
print(valueMap);
//people = List<Person>.from(valueMap.map((i) => Person.fromJson(i)));
//message.forEach((name, amount) => people.add(Person(name: name, amount: amount)));
});
}
var listAmounts = valueMap.values.toList();
var listNames = valueMap.keys.toList();
print(listAmounts[0]);
print(listNames[0]);
for (int i = 0; i < listAmounts.length; i++) {
Person newPerson =
new Person(name: listNames[i], amount: double.parse(listAmounts[i]));
coins.add(newPerson);
print('=========');
print(newPerson.name);
print(newPerson.amount.toString());
print('=========');
}
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
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