how to get value of item in array of list and make them independent list - list

I have list like example below, I want to get value of nameCategory and make them to List
List<Categories> iconCategory= [
Categories(
iconPath: 'assets/images/icons/IncomeIcon/001-salary.svg',
nameCategory: 'Salary',
),
Categories(
iconPath: 'assets/images/icons/IncomeIcon/002-interest.svg',
nameCategory: 'Interest',
),
Categories(
iconPath: 'assets/images/icons/IncomeIcon/003-award.svg',
nameCategory: 'Award',
)];
to list like example below but the data is from array list above
how I can do that
List<String> myCategory = ['Salary','Interest','Award'];

You can simply use the map method to achieve this:
List<String> myCategory = mycategories.map((e) => e.nameCategory).toList();
print(myCategory); // Prints [Salary, Interest, Award]

this will give you what you need
List<Categories> s1 = [];
List<String> ss = [];
result!.map((e) {
ss.add(e.nameCategory);
});

Related

How to count category value of array of List

let's say I have a list like the example below
<Categories>myList = [
Categories(
nameCategory: 'Book',
amount: '20'
),
Categories(
nameCategory: 'Book',
amount: '40'
),
Categories(
nameCategory: 'Food',
amount: '20'
),
Categories(
nameCategory: 'Food',
amount: '15'
),
];
How I can combine the duplicate values of that list and count the value of the list based on name ??
I can combine the list and the count value of the list but that only works just in a general list like sum total
what I want to do is make a new List but only combine several parts that share the same property like the same category or same class like that
this is an example what I want to achieve
<Categories> anotherList= [
Categories(
nameCategory: 'Book',
amount: '60'
),
Categories(
nameCategory: 'Food',
amount: '35'
),
];
I would replace your List<Categories> with a Map<String, Categories>. Then you can easily look up the Categories object given its name and mutate the existing Categories object. For example, something like:
var mergedCategories = <String, Categories>{};
for (var categories in myList) {
var name = categories.nameCategory;
var amount = categories.amount;
(mergedCategories[name] ??= Categories(nameCategory: name, amount: 0))
.amount += amount;
}
You're essentially trying to get an aggregate value from a list, which is what List.fold is meant to help with.
Here's an example of how you might use it:
class Category {
final String name;
int amount;
Category({required this.name, required this.amount});
String toString() => "Category(name: $name, amount: $amount)";
}
void main() {
final categories = [
Category(
name: 'Book',
amount: 20
),
Category(
name: 'Book',
amount: 40
),
Category(
name: 'Food',
amount: 20
),
Category(
name: 'Food',
amount: 15
),
];
/**
* Here is where the aggregation is done
*/
final List<Category> aggregated = categories.fold([], (list, item) {
try {
// Check whether the category is already in the aggregate
final existingCategory = list.firstWhere((c) => c.name == item.name);
// Category is already in the list, so just add the amount of the current item.
existingCategory.amount += item.amount;
return list;
} catch (_) {
// The category has not yet been added - so add it here
list.add(item);
return list;
}
});
print(aggregated);
}
I've changed your category class a bit for simplicity, but the principle should be the same. You can read more about the fold function here: https://api.dart.dev/stable/2.13.4/dart-core/Iterable/fold.html
A pretty straightforward method is by using the groupBy function provided by the collection.dart package.
import 'package:collection/collection.dart';
groupBy<Categories, String>(list, (c) => c.nameCategory).values.map(
(list) => list.reduce(
(a, b) => new Categories(a.nameCategory, a.amount + b.amount)
)
);

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

groovy: create a list of values with all strings

I am trying to iterate through a map and create a new map value. The below is the input
def map = [[name: 'hello', email: ['on', 'off'] ], [ name: 'bye', email: ['abc', 'xyz']]]
I want the resulting data to be like:
[hello: ['on', 'off'], bye: ['abc', 'xyz']]
The code I have right now -
result = [:]
map.each { key ->
result[random] = key.email.each {random ->
"$random"
}
}
return result
The above code returns
[hello: [on, off], bye: [abc, xyz]]
As you can see from above, the quotes from on, off and abc, xyz have disappeared, which is causing problems for me when i am trying to do checks on the list value [on, off]
It should not matter. If you see the result in Groovy console, they are still String.
Below should be sufficient:
map.collectEntries {
[ it.name, it.email ]
}
If you still need the single quotes to create a GString instead of a String, then below tweak would be required:
map.collectEntries {
[ it.name, it.email.collect { "'$it'" } ]
}
I personally do not see any reasoning behind doing the later way. BTW, map is not a Map, it is a List, you can rename it to avoid unnecessary confusions.
You could convert it to a json object and then everything will have quotes
This does it. There should/may be a groovier way though.
def listOfMaps = [[name: 'hello', email: ['on', 'off'] ], [ name: 'bye', email: ['abc', 'xyz']]]
def result = [:]
listOfMaps.each { map ->
def list = map.collect { k, v ->
v
}
result[list[0]] = ["'${list[1][0]}'", "'${list[1][1]}'"]
}
println result

Lists AS value of a Map in Dart

I want to create a map of members, but every membres have 3 propreties : first name, last name, and username. How can I create like a list of liste, but with a map.
So I want to have something like :
var membres= {['lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'],
['lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'],
};
As you know, this code doesn't work. But it explain pretty well what I am trying to do.
I think you are confusing the two constructs here.
Read this introduction to the language: http://www.dartlang.org/docs/dart-up-and-running/ch02.html#lists
A list is a list of elements which can be denoted with the shorthand [...] syntax:
var list = [1, 2, "foo", 3, new Date.now(), 4];
Whereas a map can be denoted with the curly brace shorthand syntax:
var gifts = { // A map literal
// Keys Values
'first' : 'partridge',
'second' : 'turtledoves',
'fifth' : 'golden rings'
};
So, let's modify your code to work:
var members = [
{
'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'
},
{
'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'
}
];
You can, for example, print the information like this:
members.forEach((e) {
print(e['firstname']);
});
If I understand your intent correctly, you want to have a list of maps. What you have is correct except you confused [ and {. The following works:
var membres = [
{'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'},
{'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'}
];
As an example, to get a list of all usernames:
print(membres.map((v) => v['username']));
If you don't really need a Map, what about using a class to improve the structure of your code :
class Member {
String firstname;
String lastname;
String username;
Member(this.firstname, this.lastname, this.username);
}
main() {
final members = new List<Member>();
members.add(new Member('Pierre', 'Bonneau', 'mariobross'));
members.add(new Member('Alex', 'Hamel', 'Queenlatifa'));
// use members
}
You mean like this?
// FirstName => LastName => Value
var lookup = new Map<String, Map<String, String>>();
// get / set values like this
void setValue(String firstName, String lastName, String value) {
if (!lookUp.containsKey(firstName))
lookUp[firstName] = new Map<String, String>();
lookUp[firstName][lastName] = value;
}
String getValue(String firstName, String lastName) {
if (!lookUp.containsKey(firstName)) return "";
return lookUp[firstName][lastName];
}
First of all you need to create a map with value as list. Dont forget to initialize it
then if you want to fill it you first need to use built in function like putIfAbsent as in dart to add first object in list and then use update to add items in list. therefore you will need two arrays. First to put elements and then to add elements in list with same key. Also you can use try catch to identify if the key is present or not to do that in one loop
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.putIfAbsent(
date_time,
() => [
{
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
}
]);
}
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.update(date_time, (value) {
value.add({
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
});
return value;
});
}