In flutter How to add a list to another list, how to delete, and recall the data? - flutter

To make my question clear:
I work in meals page layout and the idea is the user will select the food item of his/her meal from a list by click on a checkbox, and after that add meal in the system.
Question is:
I need to create a list (growth list) that contains all the food item information that the user is select it and after the user is press "add" button I will save each single food item' information from list to the database. I try to match ways but it not work. and I don't understand the wrong. I try a list and the problem is was how to callback the single food item's information. After that, now I try nested list and the problem is was how to insert or add the food item's information to a list.
here a code of nested list:
List<List> food= [];
add when click on checkbox:
List foo=[widget.id,widget.name,widget.carbs,widget.Amunt];
//when try with insert:
food.insert(index, foo);
//when try with add:
food[index].add(foo);
remove:
food.removeAt(index);
callback:
for(int i=0;i<food.length;i++){
Item vat= Item(food[i][0],mealId, dbEmail,food[i][1], food[i][2], food[i][3]);
var dbItem= await helper.insertFood(Item);
}
here an old code of list:
List food;
add when click on checkbox:
List foo=[widget.id,widget.name,widget.carbs,widget.Amunt];
varty.add({ 'id':widget.id,'name':widget.name,'carb':widget.carbs,'amunt':widget.Amunt});
remove:
food.removeAt(index);
callback:
for(int i=0;i<food.length;i++){
Item vat= Item(food[i]['id'],mealId,dbEmail,food[i]['name'],food[i]['carb'],food[i]['amunt']);
var dbItem= await helper.insertFood(Item);
}
I think there's something I didn't use the right way but I don't know what it is!
So, I would be grateful for any help.

Related

How to remove duplicate List items having the same Map Key in Flutter/Dart?

I have a list where I add Map values when the user clicks a button. The user is presented with 3 buttons, each button has the same questionId (such as 3) but the answerValue is different for each button. Everytime a user clicks one button, a Map with question id and answerValue is added to a list.
My list looks like this below if the user clicked all three buttons having the same Question Id:
{{questionId: 4, answerValue : 8}, {questionId: 4, answerValue : 7}, {questionId: 4, answerValue : 8}}
so the problem I am facing now is I have duplicate items as you can see from above. Instead of replacing the answerValue, the list is adding more and more items as many times the user is clicking the buttons. What i want to achieve here is if the questionId is same, the list should replace that item instead of creating a new list entry. I tried using set() and other answers found in stackoverflow but most of them is just for a single list item and I could not achieve what i was looking for. Check below for code:
//This generates a map
var map = new QuesNValues(questionId: widget.ques.questions[widget.index].question.questionOptions[i].questionId, questionOptionId: val).toJson();
// Output: {questionId: 4, questionOptionId: 9}
This map is then added to a list:
selectedQuesValuesList.add(map);
I've tried using for statements for items in list but i simple could not make it work. I just need the list to replace values having the same questionId instead of creating new items.
Before adding a response to your list, you can clean it :
selectedQuesValuesList.removeWhere((m) => m.questionId == id);

Accordion dropdown filtering through ion search bar

Hi I just created the ionic accordion dropdowns by following a tutorial blog link which used widgets for creating an accordion dropdowns, Below is the link of that blog.
http://masteringionic.com/blog/2019-01-27-creating-a-simple-accordion-widget-in-ionic-4/
updated: here is the my project demo link https://stackblitz.com/github/dSaif/search-accordion
Everything is working perfect, but i want to add Ion-searchbar at the top of the accordions sothat the dropdowns gets filter by inputing text.
please assist me how can i do that. Thank you.
You are going to have to create a variable in your homepage to store your filtered results. Then you need to have a filter function that will take the input from the search bar and filter your master list. Keep in mind you should not set the new variable to the master list, this could cause issues due to object referencing.
So you should have something like
in your html
<ion-searchbar placeholder="Search a name." [(ngModel)]="searchValue" (ionChange)="filterList()"></ion-searchbar>
In your ts file
searchValue: string = '';
filteredList: Array<{ name: string, description: string, image: string }> = this.technologies;
// function called in the html whenever you change the ion searchbar value
private filterList(){
//Make a variable so as to avoid any flashing on the screen if you set it to an empty array
const localFilteredList = []
this.technologies.forEach(currentItem => {
//here goes your search criteria, in the if statement
if(currentItem.name && currentItem.name.toLowerCase().includes(this.searchValue.toLowerCase())) {
localFilteredList.push(currentItem);
}
});
//finally set the global filter list to your newly filtered list
this.filteredList = localFilteredList;
}
You also need to make sure to reference the filterList variable instead of the current one you are referencing.

Dynamically Add Item to DropDownList in a form

I have a question and maybe someone could help me find the best solution. I want a user to be able to add items to a drop down list dynamically in a form. I have a form with text boxes and drop down lists and want the user to be able to add items to the drop down list if they don't find it. I would make the drop down lists text boxes but I want to try and keep the names consistent. An example of a form would be have the user enter a name and then have drop down lists for colors and shapes. If the user does not see the color in the drop down I want them to be able to click a link next to the drop down and enter the name or the color. Another link to add shapes to the drop down list.
I'm trying to do this in an MVC Razor environment. I tried using partial views by having the link open a modal box of a partial view to enter the name, but then I have a form within a form and cannot submit the inner form. If I open a small window to enter the name then how do I add it back to the original parent window form without loosing what they already entered in the text box? I know there has to be a good solution out there.
If you want the users new input to be saved for later use, you could use Ajax to submit the new data into the database, and then have the controller return a partial view with your new dropdown.
So your dropdown would be an action Like this:
public PartialViewResult Dropdown()
{
var model = new DropdownModel()
{
Data = yourdata;
}
return PartialView("Dropdown.cshtml", model)
}
And your action to insert new data would look something like this:
public PartialViewResult AddDataToDropdown(string data)
{
var newDropdown = repository.AddData(data);
var model = new DropdownModel()
{
Data = newDropdown;
}
return PartialView("Dropdown.cshtml", model)
}
So bascially, you can resplace the HTML in the div that contains the dropdown with Ajax like this:
$(".someButton").on("click", function () {
var newData = ("$someTextbox").val();
$.ajax({
url: "/YourController/AddDataToDropdown",
type: "GET",
data: { data: newData}
})
.success(function (partialView) {
$(".someDiv").html(partialView);
});
});
This way you save the data and the dropdown is refreshed without refreshing the entire page

Storing appended elements to localStorage

I'm a teacher and creating a page to organize my lesson plans. There should be the ability to add new lessons (li) and new weeks (ul). The lessons are sortable between each of the weeks. Each newly added item will then be saved to localStorage.
So far, I'm able to create the lessons and new weeks. The sortable function works. The save function works... except that it will not save any of the new weeks (ul). When I refresh, the new lessons (li) are still on the page, but the new weeks (ul) are gone.
$("#saveAll").click(function(e) {
e.preventDefault();
var listContents = [];
$("ul").each(function(){
listContents.push(this.innerHTML);
})
localStorage.setItem('todoList', JSON.stringify(listContents));
});
$("#clearAll").click(function(e) {
e.preventDefault();
localStorage.clear();
location.reload();
});
loadToDo();
function loadToDo() {
if (localStorage.getItem('todoList')){
var listContents = JSON.parse(localStorage.getItem('todoList'));
$("ul").each(function(i){
this.innerHTML = listContents [i];
})
}
}
I created a fiddle here.
You can click the "Add New Week" button and then click the "Create Lesson" button and drag the new lesson into one of the weeks. After clicking "Save All", only the first week is saved.
I can't seem to figure out what's missing.
It's saving correctly, but since the page only has one <ul> element initially, that is the only one that gets populated in loadToDo(). (listContents has more than one element, but $("ul").each(...) only iterates over one element.)
There is a quick band-aid you can use to resolve this. Refactor your #new-week-but click handler into a named function:
function addNewWeek() {
var x = '<ul class="sortable weeklist"></ul>';
$(x).appendTo('.term').sortable({connectWith: '.sortable'});
}
$('#new-week-but').click(addNewWeek);
Then add this block after you fetch the array from storage but before you enumerate the <ul> elements:
var i;
for (i = 2; i < listContents.length; ++i) {
addNewWeek();
}
This will add the required number of <ul> elements before attempting to populate them.
I chose to initialize i to two because this creates two fewer than the number of elements in listContents. We need to subtract one because there is a <ul> in .term when the page loads, and another because the <ul id="new-lesson-list"> contents also get saved in listContents. (Consider filtering that element out in your #saveAll click handler.)
(Note that this requires merging all of your $(document).ready() functions into one big function so that addNewWeek() is visible to the rest of your code.)
Suggestions to improve code maintainability:
Give each editable <ul> a CSS class so that they can be distinguished from other random <ul> elements on the page. Filter for this class when saving data so that the "template" <ul> doesn't get saved, too.
Remove the one default editable <ul> from the page. Instead, in your loadToDo() function, add an else block to the if block and call addNewWeek() from the else block. Also, call it if listContents.length == 0. This will prevent duplicating the element in the HTML source (duplication is bad!) and having to account for it in your load logic.
If you implement both of these then you can initialize i to 0 instead of 2 in my sample code, which is a lot less weird-looking (and less likely to trip up future maintainers).

How to implement Expand/Collapse for a table with Multiple columns - GWT - Google Visualization API

I have list of Items with parent child relation.
At present I am displaying them in a single table. In each row, fist column starts with number of '-'s indicating the depth.
Now I want show only top level items first and with a '+' button before that.
When the user clicks on the '+' button it should turn to '-' and the children of that particular Item need to be displayed.
So, Please help me how to implement that Expand and Collapse functionality in GWT.
EDIT:
I have my Items in a tree format.
Now I am creating a DataTable and Displaying it using GoogleTableChart
The code as follows:
DataTable data = DataTable.create();
data.addColumn(ColumnType.STRING, "Item Name ");
data.addColumn(ColumnType.STRING, "Item Id");
data.addColumn(ColumnType.NUMBER, "Quantity");
data.addColumn(ColumnType.NUMBER, "Price ($)");
data.addRows(treeList.size());
int i=0;
while(i<treeList.preOrderTraversal().size())
{
int col=0;
Item d=(Item) treeList.preOrderTraversal().get(i);
int level=d.getLevel();
//setting values to DataTable goes here
i++;
}
GoogleTableChart tblChart = new GoogleTableChart();
vPanel.add(tblChart.showFlexibleTable1(data));
Here is my solution:
I create Nested VertialPanels for each Item. And put the reference in a map.
Hide/unhide the panels based on clicks.
For root Item take one panel and add all its children.
After adding one child, add all its children to another panel,hide it and add to root panel.
repeat the steps recursively.
before each row place put (+/-) label and add click handler which take item id as parameter.
when these lables are clicked, based on the status we hide/unhide the panels, taken from the map.
Any Better Solution ... ??