Using Animated Switcher, which are stored in a List - list

I want to have a Scaffold, which contains a variable amount of Elements in a ListView. The Elements are all equal, just a few values are different. So I made a Scaffold for those Elements and want to store them in a growable List. My Problem is, that the AnimatedSwitcher doesn't work anymore when I retrieve it from the List.
bool Boolean = false; <br/>
List<Widget> widgets = [ AnimatedSwitcher(<br/>duration: Duration(seconds: 2), <br/>child: Boolean ? childrenOne : childrenTwo) ]
body: ListView( <br/>
children: widgets
),

Related

How do I loop and render through a list of predefined widgets?

So I have a list of predefined choices that I defined below
final List<DropdownMenuItem> grades = <DropdownMenuItem>[
DropdownMenuItem(value: "Highschool", child: Text('Highschool')),
DropdownMenuItem(value: "Senior High", child: Text('Senior High')),
DropdownMenuItem(value: "College", child: Text('College'))];
And what I want to do is traverse through the list and put it under the drop down menu
Form(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: defState,
onChanged: (String? newValue) {
setState(() {
defState = newValue!;
});
},
items: grades.map((items) => return items),
hint: Text("Grade"),
),
)),
)
But it's giving me these two errors
The argument type 'Iterable<DropdownMenuItem<dynamic>>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'.
Unexpected text 'return'.
Try removing the text.
Is there a way to iterate the list so I can just immediately return?
A few things:
First, arrow functions don't need the return keyword. For example, the following 2 functions are equivalent:
grades.map((_) => 'hello')
grades.map((_) {
return 'hello';
})
Secondly, the error message says: "you gave me an Iterable<DropdownMenuItem<dynamic>>, but I need a List<DropdownMenuItem<String>>".
You're creating a DropdownButton<String>, which takes a List<DropdownMenuItem<String>> as its items parameter, but you pass in grades.map( ... ).
map() is defined in Iterable, and has the following signature:
Iterable<T> map<T>(T f(E e))
This is a little bit opaque, but crucially, it returns an Iterable<T>, where T is the return type of the function you pass in, for example:
List<int> ints = [1, 2, 3];
Iterable<String> strings = ints.map((i) => i.toString());
To fix your problem, you should do the following:
instead of having a final field with widgets inside, make it a function. You should avoid caching widgets like this (unless they are const) as it interferes with hot-reload. Importantly, the function should also specify the type of DropdownMenuItem it returns:
List<DropdownMenuItem<String>> get grades => [
DropdownMenuItem<String>(...),
...
]
Your map function is invalid, but if you remove the return keyword, it would be (items) => items, which is the identity function (i.e. it does nothing). You can remove this and it will work.
Alternatively, if you want to call some function, you then need to call toList() on the result, since items expects a list:
items: grades,
// or
items: grades.map((grade) => ...).toList(),
Change the type of grades list to List<DropdownMenuItem<String>>:
final List<DropdownMenuItem<String>> grades = [
DropdownMenuItem(value: "Highschool", child: Text('Highschool')),
DropdownMenuItem(value: "Senior High", child: Text('Senior High')),
DropdownMenuItem(value: "College", child: Text('College'))
];
And just use grades instead of a map:
DropdownButton<String>(
value: defState,
onChanged: (String? newValue) {
setState(() {
defState = newValue!;
});
},
items: grades,
hint: Text("Grade"),
),

Flutter - how to make an array of objects

Edit:
class Transactions {
final String id;
final double amount;
final String date;
const Transactions({
#required this.id,
#required this.amount,
#required this.date,
});}
I am trying to ad a transaction to the current month . When the user adds a transaction based on the current moth is I would like to add that transaction to the array,e
so I want to make a list of list of Transactions
this is what i have tried :
List<List> _userTransactions = [
List<Transactions> jan= [];
List<Transactions> feb= [];
List<Transactions> mar= [];
List<Transactions> apr= [];
List<Transactions> may= [];
.....
];
Edit:
already answered
you might want try this one:
final grid = List<List<int>>.generate(
size, (i) => List<int>.generate(size, (j) => i * size + j));
If all you want is to initialize a list of hard-coded integers, you can do:
var list = [
[1, 2, 3],
[4, 5, 6]
];
You can specify the type instead of var if you want, it is List<List<int>>.
Or, if you want to generate a grid, you can either use a for loop with the add function, or use generate as per mra9776's answer.
Here we have a class with name as Transactions
So to make the list of Transactions objects we have to create list which is of type Transactions
In the below code part we created a List
of type Transactions and added objects to them by creating them with the help of new variable
List<Transactions> _userTransactions = [
new Transactions(100, 5000, "4-10-2020"),
new Transactions(101, 5000, "4-11-2020")
];
for more information about creation of objects and adding them to the List
please click the link https://kodeazy.com/flutter-array-userdefined-class-objects/

Display items in a list containing a specific name - flutter

In this list, I want to display out all the items that contains this specific name.
My list items: ['US', 'SG', 'US']
print(list.contains("US"));
Using .contains() returns me a true or false but it doesn’t return me the list of strings that contains that. I want to only extract out the items that has 'US' from the list. In this case, there's 2 of it. Please help!
You can try doing it the following way -
List<String> myList = ['US', 'SG', 'US'];
print(myList.where((item) => item.contains("US")));
You can also display it directly inside a Text widget in the following way -
Text(
myList.where((item) => item.contains("US")).join(" "),
//The join function joins the elements of the Iterable into a single string with the separator provided as an argument.
),
Hope this helps!
UPDATE:
To display each of the word separately as a list you can display them inside a Column in the following way -
Column(
children: myList.map((value) {
if(value.contains("US")){
return Text(value,);
} else {
return Container();
//Return an empty Container for non-matching case
}
}).toList(),
)
The same thing can be used inside a ListView instead of Column if you want it to be scrollable.
Something like this?
var myList = ['US', 'SG', 'US'];
myList.forEach((w){
if(w == "US")
print(w);
});
To show:
class SO extends StatelessWidget {
var myList = ['US', 'SG', 'US'];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisSize: MainAxisSize.min,
children: myList.where((w) => w == "US").map((w) => Text(w)).toList(),
),
);
}
}
or for a single line display use, Text instead of Column widget mentioned above
Text(myList.where((w) => w.contains("US")).join(" "))
If you are using "list.contains". It will only show the list exist or not , If you want to print the value you have to use follow :
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];fruits.forEach((fruit) => print(fruit)); // => banana pineapple watermelon
If you want to print just banana then you can use this
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];fruits.(fruit) => print(fruit[0]); // => banana

How do I query CloudSearch for a document that contains more than one value in a list or array?

example documents:
{
"name":"Bob Belcher",
"children":[
"Tina",
"Louise",
"Gene"
]
}
I want to find a document by asking:
contains children "Tina" AND contains children "Louise"
Similarly how can I do:
contains children "Tina" AND NOT contains children "Jack"
Can this be done with child objects instead of strings?
contains children with name="Tina" AND contains children with name="Louise"
example documents:
{
"name":"Bob Belcher",
"children":[
{
"name":"Tina"
},
{
"name":"Louise"
},
{
"name":"Gene"
}
]
}
One more, can we do this many layers deep?
{
"name":"Bob Belcher",
"children":[
{
"name":"Tina",
"pets":[
"Spot",
"Snowball"
]
},
{
"name":"Louise",
"pets":[
"Liz"
]
},
{
"name":"Gene"
}
]
}
Can I ask something like:
Contains children that contains pets "Spot" AND Contains children that contains pets "Snowball"
1) The attribute children defined as SET Dynamodb data type, it is possible to filter with CONTAINS and NOT CONTAINS. Example:-
FilterExpression: " contains (product, :productSet) AND not contains (product, :productSetNotContains)",
ExpressionAttributeValues : {
':key1' : 2016,
':titleval' : "The Big New Movie 1",
':productSet' : "milk",
':productSetNotContains' : "egg"
}
2) The attribute children defined as LIST DynamoDB data type, it is possible to filter using CONTAINS.
var childrenTina = {"name":"Tina"};
var childrenLouise = {"name":"Louise"};
FilterExpression: " contains (children, :childrenTina) AND contains (children, :childrenLouise) ",
ExpressionAttributeValues : {
':key1' : 2016,
':titleval' : "The Big New Movie 1",
':childrenTina' : childrenTina,
':childrenLouise' : childrenLouise
}
3) For deeply layered array, filter can be done using CONTAINS if the entire value of an element is known i.e. in order to match Tina, the value of Pets attributes are also required.
In DynamoDB terms, the below structure means there is a MAP inside LIST i.e. each element in the LIST is a MAP. As long as the entire MAP data is available, the CONTAINS function can be used to filter the data.
"name":"Tina",
"pets":[
"Spot",
"Snowball"
]

right align dynamic column of datatype number in iggrid

I am using Ignite UI grid.
The columns is dynamically build from the database like this:-
$.post('/Main/GetColumns',function(data){
$("#mygrid").igGrid({
columns: data,
width: "100%",
height: "100%",
})
});
The problem is that i dont know which of the column will be of datatype number since data is comming from database for columns and i have to right align the numeric columns.
The only code i have found is
args.owner.element.find("tr td:nth-child(3)").css("text-align", "right");
to set 3rd column as right align.
Since i dont know the column order, i am only left to check for datatype and right align the column,
Is there any way to align column on basis of datatype or any other method to do this?
The data type if the column is used for it's representation(formatting) and editing behavior, but there's no extra markup generated that you can use to target with styling.
However, you are building column definitions server side, where you know exactly what type each column is while creating its definition, no?
Update: It's been a while since the original answer and for future reference you can use the columnCssClass to apply your class to the actual TD rather than the template. The latter is still a valid option for advanced tinkering.
Easiest way I can think of is through Column templates - this way you can add whatever styling / formatting to the columns. For example, based of whatever logic you need, you return some columns as:
{
key: 'status',
dataType: 'bool',
headerText: 'Status',
template: '<div class="rightAlign"> ${status} </div>'
}
You apply "text-align:right;" though the class and skip adding template for columns that should be with default look. Since this definition is generated on the server (imagine my example uses Node.js :P ) you can have those templates static, or create them differently each time - it's up to you.
JSFiddle: http://jsfiddle.net/damyanpetev/wsZ8c/
Note: Make sure you use a block (div,p) in this case as you need something that will take up the entire grid cell in order to align text inside.
If that solution doesn't fit, you will have to go through columns and apply styling on the client in a similar way you were thinking of.
Here is how I dynamically align the text in the columns in the infragistics igHierarchicalGrid according to their data types:
$("#grid1").on("iggriddatarendered", function (event, args) {
var columns = $("#grid1").igHierarchicalGrid("option", "columns");
//var RDate = $("#grid1").igHierarchicalGrid("getCellValue", 1, 1);
var columnIndex = 0;
var trtd = 2;
for (var idx = 0; idx < columns.length; idx++) {
if (columns[idx].dataType == "number" || columns[idx].dataType == "double")
args.owner.element.find("tr td:nth-child(" + trtd + ")").css("text-align", "right");
if (columns[idx].dataType == "string" || columns[idx].dataType == "date")
args.owner.element.find("tr td:nth-child(" + trtd + ")").css("text-align", "left");
columnIndex++;
trtd = columnIndex + 2;
}
});
As you see I am starting with vartd = 2 and this is because there are 2 elements in the table
(I use hierachcical grid) before the columns in the grid are available. You must debug and investigate if in your case
the columns of the grid are coming after the second DOM element or after the first.
In easy way you can add css into columnCssClass property and applied into grid where you were define column information
Style:
<style>
.right-align {
text-align: right;
}
.left-align {
text-align: left;
}
.center-align {
text-align: center;
}
</style>
and grid code snippet:
{ headerText: 'Option', key: "Option", dataType: "string", width: "10%", hidden: true },
{ headerText: 'ID', key: "Program_Id", dataType: "string", width: "10%", columnCssClass: "right-align" },
{ headerText: 'Desc', key: "Program_Des", dataType: "string", width: "10%", columnCssClass: "left-align" },
{ headerText: 'Status', key: "program_Status", dataType: "Bool", width: "10%", columnCssClass: "center-align" },